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