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