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