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