github.com/akaros/go-akaros@v0.0.0-20181004170632-85005d477eab/src/time/time.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package time provides functionality for measuring and displaying time. 6 // 7 // The calendrical calculations always assume a Gregorian calendar. 8 package time 9 10 import "errors" 11 12 // A Time represents an instant in time with nanosecond precision. 13 // 14 // Programs using times should typically store and pass them as values, 15 // not pointers. That is, time variables and struct fields should be of 16 // type time.Time, not *time.Time. A Time value can be used by 17 // multiple goroutines simultaneously. 18 // 19 // Time instants can be compared using the Before, After, and Equal methods. 20 // The Sub method subtracts two instants, producing a Duration. 21 // The Add method adds a Time and a Duration, producing a Time. 22 // 23 // The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. 24 // As this time is unlikely to come up in practice, the IsZero method gives 25 // a simple way of detecting a time that has not been initialized explicitly. 26 // 27 // Each Time has associated with it a Location, consulted when computing the 28 // presentation form of the time, such as in the Format, Hour, and Year methods. 29 // The methods Local, UTC, and In return a Time with a specific location. 30 // Changing the location in this way changes only the presentation; it does not 31 // change the instant in time being denoted and therefore does not affect the 32 // computations described in earlier paragraphs. 33 // 34 // Note that the Go == operator compares not just the time instant but also the 35 // Location. Therefore, Time values should not be used as map or database keys 36 // without first guaranteeing that the identical Location has been set for all 37 // values, which can be achieved through use of the UTC or Local method. 38 // 39 type Time struct { 40 // sec gives the number of seconds elapsed since 41 // January 1, year 1 00:00:00 UTC. 42 sec int64 43 44 // nsec specifies a non-negative nanosecond 45 // offset within the second named by Seconds. 46 // It must be in the range [0, 999999999]. 47 nsec int32 48 49 // loc specifies the Location that should be used to 50 // determine the minute, hour, month, day, and year 51 // that correspond to this Time. 52 // Only the zero Time has a nil Location. 53 // In that case it is interpreted to mean UTC. 54 loc *Location 55 } 56 57 // After reports whether the time instant t is after u. 58 func (t Time) After(u Time) bool { 59 return t.sec > u.sec || t.sec == u.sec && t.nsec > u.nsec 60 } 61 62 // Before reports whether the time instant t is before u. 63 func (t Time) Before(u Time) bool { 64 return t.sec < u.sec || t.sec == u.sec && t.nsec < u.nsec 65 } 66 67 // Equal reports whether t and u represent the same time instant. 68 // Two times can be equal even if they are in different locations. 69 // For example, 6:00 +0200 CEST and 4:00 UTC are Equal. 70 // This comparison is different from using t == u, which also compares 71 // the locations. 72 func (t Time) Equal(u Time) bool { 73 return t.sec == u.sec && t.nsec == u.nsec 74 } 75 76 // A Month specifies a month of the year (January = 1, ...). 77 type Month int 78 79 const ( 80 January Month = 1 + iota 81 February 82 March 83 April 84 May 85 June 86 July 87 August 88 September 89 October 90 November 91 December 92 ) 93 94 var months = [...]string{ 95 "January", 96 "February", 97 "March", 98 "April", 99 "May", 100 "June", 101 "July", 102 "August", 103 "September", 104 "October", 105 "November", 106 "December", 107 } 108 109 // String returns the English name of the month ("January", "February", ...). 110 func (m Month) String() string { return months[m-1] } 111 112 // A Weekday specifies a day of the week (Sunday = 0, ...). 113 type Weekday int 114 115 const ( 116 Sunday Weekday = iota 117 Monday 118 Tuesday 119 Wednesday 120 Thursday 121 Friday 122 Saturday 123 ) 124 125 var days = [...]string{ 126 "Sunday", 127 "Monday", 128 "Tuesday", 129 "Wednesday", 130 "Thursday", 131 "Friday", 132 "Saturday", 133 } 134 135 // String returns the English name of the day ("Sunday", "Monday", ...). 136 func (d Weekday) String() string { return days[d] } 137 138 // Computations on time. 139 // 140 // The zero value for a Time is defined to be 141 // January 1, year 1, 00:00:00.000000000 UTC 142 // which (1) looks like a zero, or as close as you can get in a date 143 // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to 144 // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a 145 // non-negative year even in time zones west of UTC, unlike 1-1-0 146 // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York. 147 // 148 // The zero Time value does not force a specific epoch for the time 149 // representation. For example, to use the Unix epoch internally, we 150 // could define that to distinguish a zero value from Jan 1 1970, that 151 // time would be represented by sec=-1, nsec=1e9. However, it does 152 // suggest a representation, namely using 1-1-1 00:00:00 UTC as the 153 // epoch, and that's what we do. 154 // 155 // The Add and Sub computations are oblivious to the choice of epoch. 156 // 157 // The presentation computations - year, month, minute, and so on - all 158 // rely heavily on division and modulus by positive constants. For 159 // calendrical calculations we want these divisions to round down, even 160 // for negative values, so that the remainder is always positive, but 161 // Go's division (like most hardware division instructions) rounds to 162 // zero. We can still do those computations and then adjust the result 163 // for a negative numerator, but it's annoying to write the adjustment 164 // over and over. Instead, we can change to a different epoch so long 165 // ago that all the times we care about will be positive, and then round 166 // to zero and round down coincide. These presentation routines already 167 // have to add the zone offset, so adding the translation to the 168 // alternate epoch is cheap. For example, having a non-negative time t 169 // means that we can write 170 // 171 // sec = t % 60 172 // 173 // instead of 174 // 175 // sec = t % 60 176 // if sec < 0 { 177 // sec += 60 178 // } 179 // 180 // everywhere. 181 // 182 // The calendar runs on an exact 400 year cycle: a 400-year calendar 183 // printed for 1970-2469 will apply as well to 2470-2869. Even the days 184 // of the week match up. It simplifies the computations to choose the 185 // cycle boundaries so that the exceptional years are always delayed as 186 // long as possible. That means choosing a year equal to 1 mod 400, so 187 // that the first leap year is the 4th year, the first missed leap year 188 // is the 100th year, and the missed missed leap year is the 400th year. 189 // So we'd prefer instead to print a calendar for 2001-2400 and reuse it 190 // for 2401-2800. 191 // 192 // Finally, it's convenient if the delta between the Unix epoch and 193 // long-ago epoch is representable by an int64 constant. 194 // 195 // These three considerations—choose an epoch as early as possible, that 196 // uses a year equal to 1 mod 400, and that is no more than 2⁶³ seconds 197 // earlier than 1970—bring us to the year -292277022399. We refer to 198 // this year as the absolute zero year, and to times measured as a uint64 199 // seconds since this year as absolute times. 200 // 201 // Times measured as an int64 seconds since the year 1—the representation 202 // used for Time's sec field—are called internal times. 203 // 204 // Times measured as an int64 seconds since the year 1970 are called Unix 205 // times. 206 // 207 // It is tempting to just use the year 1 as the absolute epoch, defining 208 // that the routines are only valid for years >= 1. However, the 209 // routines would then be invalid when displaying the epoch in time zones 210 // west of UTC, since it is year 0. It doesn't seem tenable to say that 211 // printing the zero time correctly isn't supported in half the time 212 // zones. By comparison, it's reasonable to mishandle some times in 213 // the year -292277022399. 214 // 215 // All this is opaque to clients of the API and can be changed if a 216 // better implementation presents itself. 217 218 const ( 219 // The unsigned zero year for internal calculations. 220 // Must be 1 mod 400, and times before it will not compute correctly, 221 // but otherwise can be changed at will. 222 absoluteZeroYear = -292277022399 223 224 // The year of the zero Time. 225 // Assumed by the unixToInternal computation below. 226 internalYear = 1 227 228 // The year of the zero Unix time. 229 unixYear = 1970 230 231 // Offsets to convert between internal and absolute or Unix times. 232 absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay 233 internalToAbsolute = -absoluteToInternal 234 235 unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay 236 internalToUnix int64 = -unixToInternal 237 ) 238 239 // IsZero reports whether t represents the zero time instant, 240 // January 1, year 1, 00:00:00 UTC. 241 func (t Time) IsZero() bool { 242 return t.sec == 0 && t.nsec == 0 243 } 244 245 // abs returns the time t as an absolute time, adjusted by the zone offset. 246 // It is called when computing a presentation property like Month or Hour. 247 func (t Time) abs() uint64 { 248 l := t.loc 249 // Avoid function calls when possible. 250 if l == nil || l == &localLoc { 251 l = l.get() 252 } 253 sec := t.sec + internalToUnix 254 if l != &utcLoc { 255 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { 256 sec += int64(l.cacheZone.offset) 257 } else { 258 _, offset, _, _, _ := l.lookup(sec) 259 sec += int64(offset) 260 } 261 } 262 return uint64(sec + (unixToInternal + internalToAbsolute)) 263 } 264 265 // locabs is a combination of the Zone and abs methods, 266 // extracting both return values from a single zone lookup. 267 func (t Time) locabs() (name string, offset int, abs uint64) { 268 l := t.loc 269 if l == nil || l == &localLoc { 270 l = l.get() 271 } 272 // Avoid function call if we hit the local time cache. 273 sec := t.sec + internalToUnix 274 if l != &utcLoc { 275 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { 276 name = l.cacheZone.name 277 offset = l.cacheZone.offset 278 } else { 279 name, offset, _, _, _ = l.lookup(sec) 280 } 281 sec += int64(offset) 282 } else { 283 name = "UTC" 284 } 285 abs = uint64(sec + (unixToInternal + internalToAbsolute)) 286 return 287 } 288 289 // Date returns the year, month, and day in which t occurs. 290 func (t Time) Date() (year int, month Month, day int) { 291 year, month, day, _ = t.date(true) 292 return 293 } 294 295 // Year returns the year in which t occurs. 296 func (t Time) Year() int { 297 year, _, _, _ := t.date(false) 298 return year 299 } 300 301 // Month returns the month of the year specified by t. 302 func (t Time) Month() Month { 303 _, month, _, _ := t.date(true) 304 return month 305 } 306 307 // Day returns the day of the month specified by t. 308 func (t Time) Day() int { 309 _, _, day, _ := t.date(true) 310 return day 311 } 312 313 // Weekday returns the day of the week specified by t. 314 func (t Time) Weekday() Weekday { 315 return absWeekday(t.abs()) 316 } 317 318 // absWeekday is like Weekday but operates on an absolute time. 319 func absWeekday(abs uint64) Weekday { 320 // January 1 of the absolute year, like January 1 of 2001, was a Monday. 321 sec := (abs + uint64(Monday)*secondsPerDay) % secondsPerWeek 322 return Weekday(int(sec) / secondsPerDay) 323 } 324 325 // ISOWeek returns the ISO 8601 year and week number in which t occurs. 326 // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to 327 // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 328 // of year n+1. 329 func (t Time) ISOWeek() (year, week int) { 330 year, month, day, yday := t.date(true) 331 wday := int(t.Weekday()+6) % 7 // weekday but Monday = 0. 332 const ( 333 Mon int = iota 334 Tue 335 Wed 336 Thu 337 Fri 338 Sat 339 Sun 340 ) 341 342 // Calculate week as number of Mondays in year up to 343 // and including today, plus 1 because the first week is week 0. 344 // Putting the + 1 inside the numerator as a + 7 keeps the 345 // numerator from being negative, which would cause it to 346 // round incorrectly. 347 week = (yday - wday + 7) / 7 348 349 // The week number is now correct under the assumption 350 // that the first Monday of the year is in week 1. 351 // If Jan 1 is a Tuesday, Wednesday, or Thursday, the first Monday 352 // is actually in week 2. 353 jan1wday := (wday - yday + 7*53) % 7 354 if Tue <= jan1wday && jan1wday <= Thu { 355 week++ 356 } 357 358 // If the week number is still 0, we're in early January but in 359 // the last week of last year. 360 if week == 0 { 361 year-- 362 week = 52 363 // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday, 364 // meaning Jan 1 of the next year is a Friday 365 // or it was a leap year and Jan 1 of the next year is a Saturday. 366 if jan1wday == Fri || (jan1wday == Sat && isLeap(year)) { 367 week++ 368 } 369 } 370 371 // December 29 to 31 are in week 1 of next year if 372 // they are after the last Thursday of the year and 373 // December 31 is a Monday, Tuesday, or Wednesday. 374 if month == December && day >= 29 && wday < Thu { 375 if dec31wday := (wday + 31 - day) % 7; Mon <= dec31wday && dec31wday <= Wed { 376 year++ 377 week = 1 378 } 379 } 380 381 return 382 } 383 384 // Clock returns the hour, minute, and second within the day specified by t. 385 func (t Time) Clock() (hour, min, sec int) { 386 return absClock(t.abs()) 387 } 388 389 // absClock is like clock but operates on an absolute time. 390 func absClock(abs uint64) (hour, min, sec int) { 391 sec = int(abs % secondsPerDay) 392 hour = sec / secondsPerHour 393 sec -= hour * secondsPerHour 394 min = sec / secondsPerMinute 395 sec -= min * secondsPerMinute 396 return 397 } 398 399 // Hour returns the hour within the day specified by t, in the range [0, 23]. 400 func (t Time) Hour() int { 401 return int(t.abs()%secondsPerDay) / secondsPerHour 402 } 403 404 // Minute returns the minute offset within the hour specified by t, in the range [0, 59]. 405 func (t Time) Minute() int { 406 return int(t.abs()%secondsPerHour) / secondsPerMinute 407 } 408 409 // Second returns the second offset within the minute specified by t, in the range [0, 59]. 410 func (t Time) Second() int { 411 return int(t.abs() % secondsPerMinute) 412 } 413 414 // Nanosecond returns the nanosecond offset within the second specified by t, 415 // in the range [0, 999999999]. 416 func (t Time) Nanosecond() int { 417 return int(t.nsec) 418 } 419 420 // YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, 421 // and [1,366] in leap years. 422 func (t Time) YearDay() int { 423 _, _, _, yday := t.date(false) 424 return yday + 1 425 } 426 427 // A Duration represents the elapsed time between two instants 428 // as an int64 nanosecond count. The representation limits the 429 // largest representable duration to approximately 290 years. 430 type Duration int64 431 432 const ( 433 minDuration Duration = -1 << 63 434 maxDuration Duration = 1<<63 - 1 435 ) 436 437 // Common durations. There is no definition for units of Day or larger 438 // to avoid confusion across daylight savings time zone transitions. 439 // 440 // To count the number of units in a Duration, divide: 441 // second := time.Second 442 // fmt.Print(int64(second/time.Millisecond)) // prints 1000 443 // 444 // To convert an integer number of units to a Duration, multiply: 445 // seconds := 10 446 // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s 447 // 448 const ( 449 Nanosecond Duration = 1 450 Microsecond = 1000 * Nanosecond 451 Millisecond = 1000 * Microsecond 452 Second = 1000 * Millisecond 453 Minute = 60 * Second 454 Hour = 60 * Minute 455 ) 456 457 // String returns a string representing the duration in the form "72h3m0.5s". 458 // Leading zero units are omitted. As a special case, durations less than one 459 // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure 460 // that the leading digit is non-zero. The zero duration formats as 0, 461 // with no unit. 462 func (d Duration) String() string { 463 // Largest time is 2540400h10m10.000000000s 464 var buf [32]byte 465 w := len(buf) 466 467 u := uint64(d) 468 neg := d < 0 469 if neg { 470 u = -u 471 } 472 473 if u < uint64(Second) { 474 // Special case: if duration is smaller than a second, 475 // use smaller units, like 1.2ms 476 var prec int 477 w-- 478 buf[w] = 's' 479 w-- 480 switch { 481 case u == 0: 482 return "0" 483 case u < uint64(Microsecond): 484 // print nanoseconds 485 prec = 0 486 buf[w] = 'n' 487 case u < uint64(Millisecond): 488 // print microseconds 489 prec = 3 490 // U+00B5 'µ' micro sign == 0xC2 0xB5 491 w-- // Need room for two bytes. 492 copy(buf[w:], "µ") 493 default: 494 // print milliseconds 495 prec = 6 496 buf[w] = 'm' 497 } 498 w, u = fmtFrac(buf[:w], u, prec) 499 w = fmtInt(buf[:w], u) 500 } else { 501 w-- 502 buf[w] = 's' 503 504 w, u = fmtFrac(buf[:w], u, 9) 505 506 // u is now integer seconds 507 w = fmtInt(buf[:w], u%60) 508 u /= 60 509 510 // u is now integer minutes 511 if u > 0 { 512 w-- 513 buf[w] = 'm' 514 w = fmtInt(buf[:w], u%60) 515 u /= 60 516 517 // u is now integer hours 518 // Stop at hours because days can be different lengths. 519 if u > 0 { 520 w-- 521 buf[w] = 'h' 522 w = fmtInt(buf[:w], u) 523 } 524 } 525 } 526 527 if neg { 528 w-- 529 buf[w] = '-' 530 } 531 532 return string(buf[w:]) 533 } 534 535 // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the 536 // tail of buf, omitting trailing zeros. it omits the decimal 537 // point too when the fraction is 0. It returns the index where the 538 // output bytes begin and the value v/10**prec. 539 func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) { 540 // Omit trailing zeros up to and including decimal point. 541 w := len(buf) 542 print := false 543 for i := 0; i < prec; i++ { 544 digit := v % 10 545 print = print || digit != 0 546 if print { 547 w-- 548 buf[w] = byte(digit) + '0' 549 } 550 v /= 10 551 } 552 if print { 553 w-- 554 buf[w] = '.' 555 } 556 return w, v 557 } 558 559 // fmtInt formats v into the tail of buf. 560 // It returns the index where the output begins. 561 func fmtInt(buf []byte, v uint64) int { 562 w := len(buf) 563 if v == 0 { 564 w-- 565 buf[w] = '0' 566 } else { 567 for v > 0 { 568 w-- 569 buf[w] = byte(v%10) + '0' 570 v /= 10 571 } 572 } 573 return w 574 } 575 576 // Nanoseconds returns the duration as an integer nanosecond count. 577 func (d Duration) Nanoseconds() int64 { return int64(d) } 578 579 // These methods return float64 because the dominant 580 // use case is for printing a floating point number like 1.5s, and 581 // a truncation to integer would make them not useful in those cases. 582 // Splitting the integer and fraction ourselves guarantees that 583 // converting the returned float64 to an integer rounds the same 584 // way that a pure integer conversion would have, even in cases 585 // where, say, float64(d.Nanoseconds())/1e9 would have rounded 586 // differently. 587 588 // Seconds returns the duration as a floating point number of seconds. 589 func (d Duration) Seconds() float64 { 590 sec := d / Second 591 nsec := d % Second 592 return float64(sec) + float64(nsec)*1e-9 593 } 594 595 // Minutes returns the duration as a floating point number of minutes. 596 func (d Duration) Minutes() float64 { 597 min := d / Minute 598 nsec := d % Minute 599 return float64(min) + float64(nsec)*(1e-9/60) 600 } 601 602 // Hours returns the duration as a floating point number of hours. 603 func (d Duration) Hours() float64 { 604 hour := d / Hour 605 nsec := d % Hour 606 return float64(hour) + float64(nsec)*(1e-9/60/60) 607 } 608 609 // Add returns the time t+d. 610 func (t Time) Add(d Duration) Time { 611 t.sec += int64(d / 1e9) 612 nsec := int32(t.nsec) + int32(d%1e9) 613 if nsec >= 1e9 { 614 t.sec++ 615 nsec -= 1e9 616 } else if nsec < 0 { 617 t.sec-- 618 nsec += 1e9 619 } 620 t.nsec = nsec 621 return t 622 } 623 624 // Sub returns the duration t-u. If the result exceeds the maximum (or minimum) 625 // value that can be stored in a Duration, the maximum (or minimum) duration 626 // will be returned. 627 // To compute t-d for a duration d, use t.Add(-d). 628 func (t Time) Sub(u Time) Duration { 629 d := Duration(t.sec-u.sec)*Second + Duration(int32(t.nsec)-int32(u.nsec)) 630 // Check for overflow or underflow. 631 switch { 632 case u.Add(d).Equal(t): 633 return d // d is correct 634 case t.Before(u): 635 return minDuration // t - u is negative out of range 636 default: 637 return maxDuration // t - u is positive out of range 638 } 639 } 640 641 // Since returns the time elapsed since t. 642 // It is shorthand for time.Now().Sub(t). 643 func Since(t Time) Duration { 644 return Now().Sub(t) 645 } 646 647 // Until returns the duration until t. 648 // It is shorthand for t.Sub(time.Now()). 649 func Until(t Time) Duration { 650 return t.Sub(Now()) 651 } 652 653 // AddDate returns the time corresponding to adding the 654 // given number of years, months, and days to t. 655 // For example, AddDate(-1, 2, 3) applied to January 1, 2011 656 // returns March 4, 2010. 657 // 658 // AddDate normalizes its result in the same way that Date does, 659 // so, for example, adding one month to October 31 yields 660 // December 1, the normalized form for November 31. 661 func (t Time) AddDate(years int, months int, days int) Time { 662 year, month, day := t.Date() 663 hour, min, sec := t.Clock() 664 return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec), t.loc) 665 } 666 667 const ( 668 secondsPerMinute = 60 669 secondsPerHour = 60 * 60 670 secondsPerDay = 24 * secondsPerHour 671 secondsPerWeek = 7 * secondsPerDay 672 daysPer400Years = 365*400 + 97 673 daysPer100Years = 365*100 + 24 674 daysPer4Years = 365*4 + 1 675 ) 676 677 // date computes the year, day of year, and when full=true, 678 // the month and day in which t occurs. 679 func (t Time) date(full bool) (year int, month Month, day int, yday int) { 680 return absDate(t.abs(), full) 681 } 682 683 // absDate is like date but operates on an absolute time. 684 func absDate(abs uint64, full bool) (year int, month Month, day int, yday int) { 685 // Split into time and day. 686 d := abs / secondsPerDay 687 688 // Account for 400 year cycles. 689 n := d / daysPer400Years 690 y := 400 * n 691 d -= daysPer400Years * n 692 693 // Cut off 100-year cycles. 694 // The last cycle has one extra leap year, so on the last day 695 // of that year, day / daysPer100Years will be 4 instead of 3. 696 // Cut it back down to 3 by subtracting n>>2. 697 n = d / daysPer100Years 698 n -= n >> 2 699 y += 100 * n 700 d -= daysPer100Years * n 701 702 // Cut off 4-year cycles. 703 // The last cycle has a missing leap year, which does not 704 // affect the computation. 705 n = d / daysPer4Years 706 y += 4 * n 707 d -= daysPer4Years * n 708 709 // Cut off years within a 4-year cycle. 710 // The last year is a leap year, so on the last day of that year, 711 // day / 365 will be 4 instead of 3. Cut it back down to 3 712 // by subtracting n>>2. 713 n = d / 365 714 n -= n >> 2 715 y += n 716 d -= 365 * n 717 718 year = int(int64(y) + absoluteZeroYear) 719 yday = int(d) 720 721 if !full { 722 return 723 } 724 725 day = yday 726 if isLeap(year) { 727 // Leap year 728 switch { 729 case day > 31+29-1: 730 // After leap day; pretend it wasn't there. 731 day-- 732 case day == 31+29-1: 733 // Leap day. 734 month = February 735 day = 29 736 return 737 } 738 } 739 740 // Estimate month on assumption that every month has 31 days. 741 // The estimate may be too low by at most one month, so adjust. 742 month = Month(day / 31) 743 end := int(daysBefore[month+1]) 744 var begin int 745 if day >= end { 746 month++ 747 begin = end 748 } else { 749 begin = int(daysBefore[month]) 750 } 751 752 month++ // because January is 1 753 day = day - begin + 1 754 return 755 } 756 757 // daysBefore[m] counts the number of days in a non-leap year 758 // before month m begins. There is an entry for m=12, counting 759 // the number of days before January of next year (365). 760 var daysBefore = [...]int32{ 761 0, 762 31, 763 31 + 28, 764 31 + 28 + 31, 765 31 + 28 + 31 + 30, 766 31 + 28 + 31 + 30 + 31, 767 31 + 28 + 31 + 30 + 31 + 30, 768 31 + 28 + 31 + 30 + 31 + 30 + 31, 769 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, 770 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, 771 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, 772 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, 773 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31, 774 } 775 776 func daysIn(m Month, year int) int { 777 if m == February && isLeap(year) { 778 return 29 779 } 780 return int(daysBefore[m] - daysBefore[m-1]) 781 } 782 783 // Provided by package runtime. 784 func now() (sec int64, nsec int32) 785 786 // Now returns the current local time. 787 func Now() Time { 788 sec, nsec := now() 789 return Time{sec + unixToInternal, nsec, Local} 790 } 791 792 // UTC returns t with the location set to UTC. 793 func (t Time) UTC() Time { 794 t.loc = UTC 795 return t 796 } 797 798 // Local returns t with the location set to local time. 799 func (t Time) Local() Time { 800 t.loc = Local 801 return t 802 } 803 804 // In returns t with the location information set to loc. 805 // 806 // In panics if loc is nil. 807 func (t Time) In(loc *Location) Time { 808 if loc == nil { 809 panic("time: missing Location in call to Time.In") 810 } 811 t.loc = loc 812 return t 813 } 814 815 // Location returns the time zone information associated with t. 816 func (t Time) Location() *Location { 817 l := t.loc 818 if l == nil { 819 l = UTC 820 } 821 return l 822 } 823 824 // Zone computes the time zone in effect at time t, returning the abbreviated 825 // name of the zone (such as "CET") and its offset in seconds east of UTC. 826 func (t Time) Zone() (name string, offset int) { 827 name, offset, _, _, _ = t.loc.lookup(t.sec + internalToUnix) 828 return 829 } 830 831 // Unix returns t as a Unix time, the number of seconds elapsed 832 // since January 1, 1970 UTC. 833 func (t Time) Unix() int64 { 834 return t.sec + internalToUnix 835 } 836 837 // UnixNano returns t as a Unix time, the number of nanoseconds elapsed 838 // since January 1, 1970 UTC. The result is undefined if the Unix time 839 // in nanoseconds cannot be represented by an int64. Note that this 840 // means the result of calling UnixNano on the zero Time is undefined. 841 func (t Time) UnixNano() int64 { 842 return (t.sec+internalToUnix)*1e9 + int64(t.nsec) 843 } 844 845 const timeBinaryVersion byte = 1 846 847 // MarshalBinary implements the encoding.BinaryMarshaler interface. 848 func (t Time) MarshalBinary() ([]byte, error) { 849 var offsetMin int16 // minutes east of UTC. -1 is UTC. 850 851 if t.Location() == &utcLoc { 852 offsetMin = -1 853 } else { 854 _, offset := t.Zone() 855 if offset%60 != 0 { 856 return nil, errors.New("Time.MarshalBinary: zone offset has fractional minute") 857 } 858 offset /= 60 859 if offset < -32768 || offset == -1 || offset > 32767 { 860 return nil, errors.New("Time.MarshalBinary: unexpected zone offset") 861 } 862 offsetMin = int16(offset) 863 } 864 865 enc := []byte{ 866 timeBinaryVersion, // byte 0 : version 867 byte(t.sec >> 56), // bytes 1-8: seconds 868 byte(t.sec >> 48), 869 byte(t.sec >> 40), 870 byte(t.sec >> 32), 871 byte(t.sec >> 24), 872 byte(t.sec >> 16), 873 byte(t.sec >> 8), 874 byte(t.sec), 875 byte(t.nsec >> 24), // bytes 9-12: nanoseconds 876 byte(t.nsec >> 16), 877 byte(t.nsec >> 8), 878 byte(t.nsec), 879 byte(offsetMin >> 8), // bytes 13-14: zone offset in minutes 880 byte(offsetMin), 881 } 882 883 return enc, nil 884 } 885 886 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. 887 func (t *Time) UnmarshalBinary(data []byte) error { 888 buf := data 889 if len(buf) == 0 { 890 return errors.New("Time.UnmarshalBinary: no data") 891 } 892 893 if buf[0] != timeBinaryVersion { 894 return errors.New("Time.UnmarshalBinary: unsupported version") 895 } 896 897 if len(buf) != /*version*/ 1+ /*sec*/ 8+ /*nsec*/ 4+ /*zone offset*/ 2 { 898 return errors.New("Time.UnmarshalBinary: invalid length") 899 } 900 901 buf = buf[1:] 902 t.sec = int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 | 903 int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56 904 905 buf = buf[8:] 906 t.nsec = int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24 907 908 buf = buf[4:] 909 offset := int(int16(buf[1])|int16(buf[0])<<8) * 60 910 911 if offset == -1*60 { 912 t.loc = &utcLoc 913 } else if _, localoff, _, _, _ := Local.lookup(t.sec + internalToUnix); offset == localoff { 914 t.loc = Local 915 } else { 916 t.loc = FixedZone("", offset) 917 } 918 919 return nil 920 } 921 922 // TODO(rsc): Remove GobEncoder, GobDecoder, MarshalJSON, UnmarshalJSON in Go 2. 923 // The same semantics will be provided by the generic MarshalBinary, MarshalText, 924 // UnmarshalBinary, UnmarshalText. 925 926 // GobEncode implements the gob.GobEncoder interface. 927 func (t Time) GobEncode() ([]byte, error) { 928 return t.MarshalBinary() 929 } 930 931 // GobDecode implements the gob.GobDecoder interface. 932 func (t *Time) GobDecode(data []byte) error { 933 return t.UnmarshalBinary(data) 934 } 935 936 // MarshalJSON implements the json.Marshaler interface. 937 // The time is a quoted string in RFC 3339 format, with sub-second precision added if present. 938 func (t Time) MarshalJSON() ([]byte, error) { 939 if y := t.Year(); y < 0 || y >= 10000 { 940 // RFC 3339 is clear that years are 4 digits exactly. 941 // See golang.org/issue/4556#c15 for more discussion. 942 return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") 943 } 944 return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil 945 } 946 947 // UnmarshalJSON implements the json.Unmarshaler interface. 948 // The time is expected to be a quoted string in RFC 3339 format. 949 func (t *Time) UnmarshalJSON(data []byte) (err error) { 950 // Fractional seconds are handled implicitly by Parse. 951 *t, err = Parse(`"`+RFC3339+`"`, string(data)) 952 return 953 } 954 955 // MarshalText implements the encoding.TextMarshaler interface. 956 // The time is formatted in RFC 3339 format, with sub-second precision added if present. 957 func (t Time) MarshalText() ([]byte, error) { 958 if y := t.Year(); y < 0 || y >= 10000 { 959 return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") 960 } 961 return []byte(t.Format(RFC3339Nano)), nil 962 } 963 964 // UnmarshalText implements the encoding.TextUnmarshaler interface. 965 // The time is expected to be in RFC 3339 format. 966 func (t *Time) UnmarshalText(data []byte) (err error) { 967 // Fractional seconds are handled implicitly by Parse. 968 *t, err = Parse(RFC3339, string(data)) 969 return 970 } 971 972 // Unix returns the local Time corresponding to the given Unix time, 973 // sec seconds and nsec nanoseconds since January 1, 1970 UTC. 974 // It is valid to pass nsec outside the range [0, 999999999]. 975 func Unix(sec int64, nsec int64) Time { 976 if nsec < 0 || nsec >= 1e9 { 977 n := nsec / 1e9 978 sec += n 979 nsec -= n * 1e9 980 if nsec < 0 { 981 nsec += 1e9 982 sec-- 983 } 984 } 985 return Time{sec + unixToInternal, int32(nsec), Local} 986 } 987 988 func isLeap(year int) bool { 989 return year%4 == 0 && (year%100 != 0 || year%400 == 0) 990 } 991 992 // norm returns nhi, nlo such that 993 // hi * base + lo == nhi * base + nlo 994 // 0 <= nlo < base 995 func norm(hi, lo, base int) (nhi, nlo int) { 996 if lo < 0 { 997 n := (-lo-1)/base + 1 998 hi -= n 999 lo += n * base 1000 } 1001 if lo >= base { 1002 n := lo / base 1003 hi += n 1004 lo -= n * base 1005 } 1006 return hi, lo 1007 } 1008 1009 // Date returns the Time corresponding to 1010 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds 1011 // in the appropriate zone for that time in the given location. 1012 // 1013 // The month, day, hour, min, sec, and nsec values may be outside 1014 // their usual ranges and will be normalized during the conversion. 1015 // For example, October 32 converts to November 1. 1016 // 1017 // A daylight savings time transition skips or repeats times. 1018 // For example, in the United States, March 13, 2011 2:15am never occurred, 1019 // while November 6, 2011 1:15am occurred twice. In such cases, the 1020 // choice of time zone, and therefore the time, is not well-defined. 1021 // Date returns a time that is correct in one of the two zones involved 1022 // in the transition, but it does not guarantee which. 1023 // 1024 // Date panics if loc is nil. 1025 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time { 1026 if loc == nil { 1027 panic("time: missing Location in call to Date") 1028 } 1029 1030 // Normalize month, overflowing into year. 1031 m := int(month) - 1 1032 year, m = norm(year, m, 12) 1033 month = Month(m) + 1 1034 1035 // Normalize nsec, sec, min, hour, overflowing into day. 1036 sec, nsec = norm(sec, nsec, 1e9) 1037 min, sec = norm(min, sec, 60) 1038 hour, min = norm(hour, min, 60) 1039 day, hour = norm(day, hour, 24) 1040 1041 y := uint64(int64(year) - absoluteZeroYear) 1042 1043 // Compute days since the absolute epoch. 1044 1045 // Add in days from 400-year cycles. 1046 n := y / 400 1047 y -= 400 * n 1048 d := daysPer400Years * n 1049 1050 // Add in 100-year cycles. 1051 n = y / 100 1052 y -= 100 * n 1053 d += daysPer100Years * n 1054 1055 // Add in 4-year cycles. 1056 n = y / 4 1057 y -= 4 * n 1058 d += daysPer4Years * n 1059 1060 // Add in non-leap years. 1061 n = y 1062 d += 365 * n 1063 1064 // Add in days before this month. 1065 d += uint64(daysBefore[month-1]) 1066 if isLeap(year) && month >= March { 1067 d++ // February 29 1068 } 1069 1070 // Add in days before today. 1071 d += uint64(day - 1) 1072 1073 // Add in time elapsed today. 1074 abs := d * secondsPerDay 1075 abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec) 1076 1077 unix := int64(abs) + (absoluteToInternal + internalToUnix) 1078 1079 // Look for zone offset for t, so we can adjust to UTC. 1080 // The lookup function expects UTC, so we pass t in the 1081 // hope that it will not be too close to a zone transition, 1082 // and then adjust if it is. 1083 _, offset, _, start, end := loc.lookup(unix) 1084 if offset != 0 { 1085 switch utc := unix - int64(offset); { 1086 case utc < start: 1087 _, offset, _, _, _ = loc.lookup(start - 1) 1088 case utc >= end: 1089 _, offset, _, _, _ = loc.lookup(end) 1090 } 1091 unix -= int64(offset) 1092 } 1093 1094 return Time{unix + unixToInternal, int32(nsec), loc} 1095 } 1096 1097 // Truncate returns the result of rounding t down to a multiple of d (since the zero time). 1098 // If d <= 0, Truncate returns t unchanged. 1099 func (t Time) Truncate(d Duration) Time { 1100 if d <= 0 { 1101 return t 1102 } 1103 _, r := div(t, d) 1104 return t.Add(-r) 1105 } 1106 1107 // Round returns the result of rounding t to the nearest multiple of d (since the zero time). 1108 // The rounding behavior for halfway values is to round up. 1109 // If d <= 0, Round returns t unchanged. 1110 func (t Time) Round(d Duration) Time { 1111 if d <= 0 { 1112 return t 1113 } 1114 _, r := div(t, d) 1115 if r+r < d { 1116 return t.Add(-r) 1117 } 1118 return t.Add(d - r) 1119 } 1120 1121 // div divides t by d and returns the quotient parity and remainder. 1122 // We don't use the quotient parity anymore (round half up instead of round to even) 1123 // but it's still here in case we change our minds. 1124 func div(t Time, d Duration) (qmod2 int, r Duration) { 1125 neg := false 1126 nsec := int32(t.nsec) 1127 if t.sec < 0 { 1128 // Operate on absolute value. 1129 neg = true 1130 t.sec = -t.sec 1131 nsec = -nsec 1132 if nsec < 0 { 1133 nsec += 1e9 1134 t.sec-- // t.sec >= 1 before the -- so safe 1135 } 1136 } 1137 1138 switch { 1139 // Special case: 2d divides 1 second. 1140 case d < Second && Second%(d+d) == 0: 1141 qmod2 = int(nsec/int32(d)) & 1 1142 r = Duration(nsec % int32(d)) 1143 1144 // Special case: d is a multiple of 1 second. 1145 case d%Second == 0: 1146 d1 := int64(d / Second) 1147 qmod2 = int(t.sec/d1) & 1 1148 r = Duration(t.sec%d1)*Second + Duration(nsec) 1149 1150 // General case. 1151 // This could be faster if more cleverness were applied, 1152 // but it's really only here to avoid special case restrictions in the API. 1153 // No one will care about these cases. 1154 default: 1155 // Compute nanoseconds as 128-bit number. 1156 sec := uint64(t.sec) 1157 tmp := (sec >> 32) * 1e9 1158 u1 := tmp >> 32 1159 u0 := tmp << 32 1160 tmp = uint64(sec&0xFFFFFFFF) * 1e9 1161 u0x, u0 := u0, u0+tmp 1162 if u0 < u0x { 1163 u1++ 1164 } 1165 u0x, u0 = u0, u0+uint64(nsec) 1166 if u0 < u0x { 1167 u1++ 1168 } 1169 1170 // Compute remainder by subtracting r<<k for decreasing k. 1171 // Quotient parity is whether we subtract on last round. 1172 d1 := uint64(d) 1173 for d1>>63 != 1 { 1174 d1 <<= 1 1175 } 1176 d0 := uint64(0) 1177 for { 1178 qmod2 = 0 1179 if u1 > d1 || u1 == d1 && u0 >= d0 { 1180 // subtract 1181 qmod2 = 1 1182 u0x, u0 = u0, u0-d0 1183 if u0 > u0x { 1184 u1-- 1185 } 1186 u1 -= d1 1187 } 1188 if d1 == 0 && d0 == uint64(d) { 1189 break 1190 } 1191 d0 >>= 1 1192 d0 |= (d1 & 1) << 63 1193 d1 >>= 1 1194 } 1195 r = Duration(u0) 1196 } 1197 1198 if neg && r != 0 { 1199 // If input was negative and not an exact multiple of d, we computed q, r such that 1200 // q*d + r = -t 1201 // But the right answers are given by -(q-1), d-r: 1202 // q*d + r = -t 1203 // -q*d - r = t 1204 // -(q-1)*d + (d - r) = t 1205 qmod2 ^= 1 1206 r = d - r 1207 } 1208 return 1209 }