Source file src/time/time.go
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), t.Compare(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. The same applies to other functions and 57 // methods that subtract times, such as [Since], [Until], [Time.Before], [Time.After], 58 // [Time.Add], [Time.Equal] and [Time.Compare]. In some cases, you may need to strip 59 // the monotonic clock to get accurate results. 60 // 61 // Because the monotonic clock reading has no meaning outside 62 // the current process, the serialized forms generated by t.GobEncode, 63 // t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic 64 // clock reading, and t.Format provides no format for it. Similarly, the 65 // constructors [time.Date], [time.Parse], [time.ParseInLocation], and [time.Unix], 66 // as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. 67 // t.UnmarshalJSON, and t.UnmarshalText always create times with 68 // no monotonic clock reading. 69 // 70 // The monotonic clock reading exists only in [Time] values. It is not 71 // a part of [Duration] values or the Unix times returned by t.Unix and 72 // friends. 73 // 74 // Note that the Go == operator compares not just the time instant but 75 // also the [Location] and the monotonic clock reading. See the 76 // documentation for the Time type for a discussion of equality 77 // testing for Time values. 78 // 79 // For debugging, the result of t.String does include the monotonic 80 // clock reading if present. If t != u because of different monotonic clock readings, 81 // that difference will be visible when printing t.String() and u.String(). 82 // 83 // # Timer Resolution 84 // 85 // [Timer] resolution varies depending on the Go runtime, the operating system 86 // and the underlying hardware. 87 // On Unix, the resolution is ~1ms. 88 // On Windows version 1803 and newer, the resolution is ~0.5ms. 89 // On older Windows versions, the default resolution is ~16ms, but 90 // a higher resolution may be requested using [golang.org/x/sys/windows.TimeBeginPeriod]. 91 package time 92 93 import ( 94 "errors" 95 "math/bits" 96 _ "unsafe" // for go:linkname 97 ) 98 99 // A Time represents an instant in time with nanosecond precision. 100 // 101 // Programs using times should typically store and pass them as values, 102 // not pointers. That is, time variables and struct fields should be of 103 // type [time.Time], not *time.Time. 104 // 105 // A Time value can be used by multiple goroutines simultaneously except 106 // that the methods [Time.GobDecode], [Time.UnmarshalBinary], [Time.UnmarshalJSON] and 107 // [Time.UnmarshalText] are not concurrency-safe. 108 // 109 // Time instants can be compared using the [Time.Before], [Time.After], and [Time.Equal] methods. 110 // The [Time.Sub] method subtracts two instants, producing a [Duration]. 111 // The [Time.Add] method adds a Time and a Duration, producing a Time. 112 // 113 // The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. 114 // As this time is unlikely to come up in practice, the [Time.IsZero] method gives 115 // a simple way of detecting a time that has not been initialized explicitly. 116 // 117 // Each time has an associated [Location]. The methods [Time.Local], [Time.UTC], and Time.In return a 118 // Time with a specific Location. Changing the Location of a Time value with 119 // these methods does not change the actual instant it represents, only the time 120 // zone in which to interpret it. 121 // 122 // Representations of a Time value saved by the [Time.GobEncode], [Time.MarshalBinary], [Time.AppendBinary], 123 // [Time.MarshalJSON], [Time.MarshalText] and [Time.AppendText] methods store the [Time.Location]'s offset, 124 // but not the location name. They therefore lose information about Daylight Saving Time. 125 // 126 // In addition to the required “wall clock” reading, a Time may contain an optional 127 // reading of the current process's monotonic clock, to provide additional precision 128 // for comparison or subtraction. 129 // See the “Monotonic Clocks” section in the package documentation for details. 130 // 131 // Note that the Go == operator compares not just the time instant but also the 132 // Location and the monotonic clock reading. Therefore, Time values should not 133 // be used as map or database keys without first guaranteeing that the 134 // identical Location has been set for all values, which can be achieved 135 // through use of the UTC or Local method, and that the monotonic clock reading 136 // has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) 137 // to t == u, since t.Equal uses the most accurate comparison available and 138 // correctly handles the case when only one of its arguments has a monotonic 139 // clock reading. 140 type Time struct { 141 // wall and ext encode the wall time seconds, wall time nanoseconds, 142 // and optional monotonic clock reading in nanoseconds. 143 // 144 // From high to low bit position, wall encodes a 1-bit flag (hasMonotonic), 145 // a 33-bit seconds field, and a 30-bit wall time nanoseconds field. 146 // The nanoseconds field is in the range [0, 999999999]. 147 // If the hasMonotonic bit is 0, then the 33-bit field must be zero 148 // and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext. 149 // If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit 150 // unsigned wall seconds since Jan 1 year 1885, and ext holds a 151 // signed 64-bit monotonic clock reading, nanoseconds since process start. 152 wall uint64 153 ext int64 154 155 // loc specifies the Location that should be used to 156 // determine the minute, hour, month, day, and year 157 // that correspond to this Time. 158 // The nil location means UTC. 159 // All UTC times are represented with loc==nil, never loc==&utcLoc. 160 loc *Location 161 } 162 163 const ( 164 hasMonotonic = 1 << 63 165 maxWall = wallToInternal + (1<<33 - 1) // year 2157 166 minWall = wallToInternal // year 1885 167 nsecMask = 1<<30 - 1 168 nsecShift = 30 169 ) 170 171 // These helpers for manipulating the wall and monotonic clock readings 172 // take pointer receivers, even when they don't modify the time, 173 // to make them cheaper to call. 174 175 // nsec returns the time's nanoseconds. 176 func (t *Time) nsec() int32 { 177 return int32(t.wall & nsecMask) 178 } 179 180 // sec returns the time's seconds since Jan 1 year 1. 181 func (t *Time) sec() int64 { 182 if t.wall&hasMonotonic != 0 { 183 return wallToInternal + int64(t.wall<<1>>(nsecShift+1)) 184 } 185 return t.ext 186 } 187 188 // unixSec returns the time's seconds since Jan 1 1970 (Unix time). 189 func (t *Time) unixSec() int64 { return t.sec() + internalToUnix } 190 191 // addSec adds d seconds to the time. 192 func (t *Time) addSec(d int64) { 193 if t.wall&hasMonotonic != 0 { 194 sec := int64(t.wall << 1 >> (nsecShift + 1)) 195 dsec := sec + d 196 if 0 <= dsec && dsec <= 1<<33-1 { 197 t.wall = t.wall&nsecMask | uint64(dsec)<<nsecShift | hasMonotonic 198 return 199 } 200 // Wall second now out of range for packed field. 201 // Move to ext. 202 t.stripMono() 203 } 204 205 // Check if the sum of t.ext and d overflows and handle it properly. 206 sum := t.ext + d 207 if (sum > t.ext) == (d > 0) { 208 t.ext = sum 209 } else if d > 0 { 210 t.ext = 1<<63 - 1 211 } else { 212 t.ext = -(1<<63 - 1) 213 } 214 } 215 216 // setLoc sets the location associated with the time. 217 func (t *Time) setLoc(loc *Location) { 218 if loc == &utcLoc { 219 loc = nil 220 } 221 t.stripMono() 222 t.loc = loc 223 } 224 225 // stripMono strips the monotonic clock reading in t. 226 func (t *Time) stripMono() { 227 if t.wall&hasMonotonic != 0 { 228 t.ext = t.sec() 229 t.wall &= nsecMask 230 } 231 } 232 233 // setMono sets the monotonic clock reading in t. 234 // If t cannot hold a monotonic clock reading, 235 // because its wall time is too large, 236 // setMono is a no-op. 237 func (t *Time) setMono(m int64) { 238 if t.wall&hasMonotonic == 0 { 239 sec := t.ext 240 if sec < minWall || maxWall < sec { 241 return 242 } 243 t.wall |= hasMonotonic | uint64(sec-minWall)<<nsecShift 244 } 245 t.ext = m 246 } 247 248 // mono returns t's monotonic clock reading. 249 // It returns 0 for a missing reading. 250 // This function is used only for testing, 251 // so it's OK that technically 0 is a valid 252 // monotonic clock reading as well. 253 func (t *Time) mono() int64 { 254 if t.wall&hasMonotonic == 0 { 255 return 0 256 } 257 return t.ext 258 } 259 260 // IsZero reports whether t represents the zero time instant, 261 // January 1, year 1, 00:00:00 UTC. 262 func (t Time) IsZero() bool { 263 return t.sec() == 0 && t.nsec() == 0 264 } 265 266 // After reports whether the time instant t is after u. 267 func (t Time) After(u Time) bool { 268 if t.wall&u.wall&hasMonotonic != 0 { 269 return t.ext > u.ext 270 } 271 ts := t.sec() 272 us := u.sec() 273 return ts > us || ts == us && t.nsec() > u.nsec() 274 } 275 276 // Before reports whether the time instant t is before u. 277 func (t Time) Before(u Time) bool { 278 if t.wall&u.wall&hasMonotonic != 0 { 279 return t.ext < u.ext 280 } 281 ts := t.sec() 282 us := u.sec() 283 return ts < us || ts == us && t.nsec() < u.nsec() 284 } 285 286 // Compare compares the time instant t with u. If t is before u, it returns -1; 287 // if t is after u, it returns +1; if they're the same, it returns 0. 288 func (t Time) Compare(u Time) int { 289 var tc, uc int64 290 if t.wall&u.wall&hasMonotonic != 0 { 291 tc, uc = t.ext, u.ext 292 } else { 293 tc, uc = t.sec(), u.sec() 294 if tc == uc { 295 tc, uc = int64(t.nsec()), int64(u.nsec()) 296 } 297 } 298 switch { 299 case tc < uc: 300 return -1 301 case tc > uc: 302 return +1 303 } 304 return 0 305 } 306 307 // Equal reports whether t and u represent the same time instant. 308 // Two times can be equal even if they are in different locations. 309 // For example, 6:00 +0200 and 4:00 UTC are Equal. 310 // See the documentation on the Time type for the pitfalls of using == with 311 // Time values; most code should use Equal instead. 312 func (t Time) Equal(u Time) bool { 313 if t.wall&u.wall&hasMonotonic != 0 { 314 return t.ext == u.ext 315 } 316 return t.sec() == u.sec() && t.nsec() == u.nsec() 317 } 318 319 // A Month specifies a month of the year (January = 1, ...). 320 type Month int 321 322 const ( 323 January Month = 1 + iota 324 February 325 March 326 April 327 May 328 June 329 July 330 August 331 September 332 October 333 November 334 December 335 ) 336 337 // String returns the English name of the month ("January", "February", ...). 338 func (m Month) String() string { 339 if January <= m && m <= December { 340 return longMonthNames[m-1] 341 } 342 buf := make([]byte, 20) 343 n := fmtInt(buf, uint64(m)) 344 return "%!Month(" + string(buf[n:]) + ")" 345 } 346 347 // A Weekday specifies a day of the week (Sunday = 0, ...). 348 type Weekday int 349 350 const ( 351 Sunday Weekday = iota 352 Monday 353 Tuesday 354 Wednesday 355 Thursday 356 Friday 357 Saturday 358 ) 359 360 // String returns the English name of the day ("Sunday", "Monday", ...). 361 func (d Weekday) String() string { 362 if Sunday <= d && d <= Saturday { 363 return longDayNames[d] 364 } 365 buf := make([]byte, 20) 366 n := fmtInt(buf, uint64(d)) 367 return "%!Weekday(" + string(buf[n:]) + ")" 368 } 369 370 // Computations on Times 371 // 372 // The zero value for a Time is defined to be 373 // January 1, year 1, 00:00:00.000000000 UTC 374 // which (1) looks like a zero, or as close as you can get in a date 375 // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to 376 // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a 377 // non-negative year even in time zones west of UTC, unlike 1-1-0 378 // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York. 379 // 380 // The zero Time value does not force a specific epoch for the time 381 // representation. For example, to use the Unix epoch internally, we 382 // could define that to distinguish a zero value from Jan 1 1970, that 383 // time would be represented by sec=-1, nsec=1e9. However, it does 384 // suggest a representation, namely using 1-1-1 00:00:00 UTC as the 385 // epoch, and that's what we do. 386 // 387 // The Add and Sub computations are oblivious to the choice of epoch. 388 // 389 // The presentation computations - year, month, minute, and so on - all 390 // rely heavily on division and modulus by positive constants. For 391 // calendrical calculations we want these divisions to round down, even 392 // for negative values, so that the remainder is always positive, but 393 // Go's division (like most hardware division instructions) rounds to 394 // zero. We can still do those computations and then adjust the result 395 // for a negative numerator, but it's annoying to write the adjustment 396 // over and over. Instead, we can change to a different epoch so long 397 // ago that all the times we care about will be positive, and then round 398 // to zero and round down coincide. These presentation routines already 399 // have to add the zone offset, so adding the translation to the 400 // alternate epoch is cheap. For example, having a non-negative time t 401 // means that we can write 402 // 403 // sec = t % 60 404 // 405 // instead of 406 // 407 // sec = t % 60 408 // if sec < 0 { 409 // sec += 60 410 // } 411 // 412 // everywhere. 413 // 414 // The calendar runs on an exact 400 year cycle: a 400-year calendar 415 // printed for 1970-2369 will apply as well to 2370-2769. Even the days 416 // of the week match up. It simplifies date computations to choose the 417 // cycle boundaries so that the exceptional years are always delayed as 418 // long as possible: March 1, year 0 is such a day: 419 // the first leap day (Feb 29) is four years minus one day away, 420 // the first multiple-of-4 year without a Feb 29 is 100 years minus one day away, 421 // and the first multiple-of-100 year with a Feb 29 is 400 years minus one day away. 422 // March 1 year Y for any Y = 0 mod 400 is also such a day. 423 // 424 // Finally, it's convenient if the delta between the Unix epoch and 425 // long-ago epoch is representable by an int64 constant. 426 // 427 // These three considerations—choose an epoch as early as possible, that 428 // starts on March 1 of a year equal to 0 mod 400, and that is no more than 429 // 2⁶³ seconds earlier than 1970—bring us to the year -292277022400. 430 // We refer to this moment as the absolute zero instant, and to times 431 // measured as a uint64 seconds since this year as absolute times. 432 // 433 // Times measured as an int64 seconds since the year 1—the representation 434 // used for Time's sec field—are called internal times. 435 // 436 // Times measured as an int64 seconds since the year 1970 are called Unix 437 // times. 438 // 439 // It is tempting to just use the year 1 as the absolute epoch, defining 440 // that the routines are only valid for years >= 1. However, the 441 // routines would then be invalid when displaying the epoch in time zones 442 // west of UTC, since it is year 0. It doesn't seem tenable to say that 443 // printing the zero time correctly isn't supported in half the time 444 // zones. By comparison, it's reasonable to mishandle some times in 445 // the year -292277022400. 446 // 447 // All this is opaque to clients of the API and can be changed if a 448 // better implementation presents itself. 449 // 450 // The date calculations are implemented using the following clever math from 451 // Cassio Neri and Lorenz Schneider, “Euclidean affine functions and their 452 // application to calendar algorithms,” SP&E 2023. https://doi.org/10.1002/spe.3172 453 // 454 // Define a “calendrical division” (f, f°, f*) to be a triple of functions converting 455 // one time unit into a whole number of larger units and the remainder and back. 456 // For example, in a calendar with no leap years, (d/365, d%365, y*365) is the 457 // calendrical division for days into years: 458 // 459 // (f) year := days/365 460 // (f°) yday := days%365 461 // (f*) days := year*365 (+ yday) 462 // 463 // Note that f* is usually the “easy” function to write: it's the 464 // calendrical multiplication that inverts the more complex division. 465 // 466 // Neri and Schneider prove that when f* takes the form 467 // 468 // f*(n) = (a n + b) / c 469 // 470 // using integer division rounding down with a ≥ c > 0, 471 // which they call a Euclidean affine function or EAF, then: 472 // 473 // f(n) = (c n + c - b - 1) / a 474 // f°(n) = (c n + c - b - 1) % a / c 475 // 476 // This gives a fairly direct calculation for any calendrical division for which 477 // we can write the calendrical multiplication in EAF form. 478 // Because the epoch has been shifted to March 1, all the calendrical 479 // multiplications turn out to be possible to write in EAF form. 480 // When a date is broken into [century, cyear, amonth, mday], 481 // with century, cyear, and mday 0-based, 482 // and amonth 3-based (March = 3, ..., January = 13, February = 14), 483 // the calendrical multiplications written in EAF form are: 484 // 485 // yday = (153 (amonth-3) + 2) / 5 = (153 amonth - 457) / 5 486 // cday = 365 cyear + cyear/4 = 1461 cyear / 4 487 // centurydays = 36524 century + century/4 = 146097 century / 4 488 // days = centurydays + cday + yday + mday. 489 // 490 // We can only handle one periodic cycle per equation, so the year 491 // calculation must be split into [century, cyear], handling both the 492 // 100-year cycle and the 400-year cycle. 493 // 494 // The yday calculation is not obvious but derives from the fact 495 // that the March through January calendar repeats the 5-month 496 // 153-day cycle 31, 30, 31, 30, 31 (we don't care about February 497 // because yday only ever count the days _before_ February 1, 498 // since February is the last month). 499 // 500 // Using the rule for deriving f and f° from f*, these multiplications 501 // convert to these divisions: 502 // 503 // century := (4 days + 3) / 146097 504 // cdays := (4 days + 3) % 146097 / 4 505 // cyear := (4 cdays + 3) / 1461 506 // ayday := (4 cdays + 3) % 1461 / 4 507 // amonth := (5 ayday + 461) / 153 508 // mday := (5 ayday + 461) % 153 / 5 509 // 510 // The a in ayday and amonth stands for absolute (March 1-based) 511 // to distinguish from the standard yday (January 1-based). 512 // 513 // After computing these, we can translate from the March 1 calendar 514 // to the standard January 1 calendar with branch-free math assuming a 515 // branch-free conversion from bool to int 0 or 1, denoted int(b) here: 516 // 517 // isJanFeb := int(yday >= marchThruDecember) 518 // month := amonth - isJanFeb*12 519 // year := century*100 + cyear + isJanFeb 520 // isLeap := int(cyear%4 == 0) & (int(cyear != 0) | int(century%4 == 0)) 521 // day := 1 + mday 522 // yday := 1 + ayday + 31 + 28 + isLeap&^isJanFeb - 365*isJanFeb 523 // 524 // isLeap is the standard leap-year rule, but the split year form 525 // makes the divisions all reduce to binary masking. 526 // Note that day and yday are 1-based, in contrast to mday and ayday. 527 528 // To keep the various units separate, we define integer types 529 // for each. These are never stored in interfaces nor allocated, 530 // so their type information does not appear in Go binaries. 531 const ( 532 secondsPerMinute = 60 533 secondsPerHour = 60 * secondsPerMinute 534 secondsPerDay = 24 * secondsPerHour 535 secondsPerWeek = 7 * secondsPerDay 536 daysPer400Years = 365*400 + 97 537 538 // Days from March 1 through end of year 539 marchThruDecember = 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 540 541 // absoluteYears is the number of years we subtract from internal time to get absolute time. 542 // This value must be 0 mod 400, and it defines the “absolute zero instant” 543 // mentioned in the “Computations on Times” comment above: March 1, -absoluteYears. 544 // Dates before the absolute epoch will not compute correctly, 545 // but otherwise the value can be changed as needed. 546 absoluteYears = 292277022400 547 548 // The year of the zero Time. 549 // Assumed by the unixToInternal computation below. 550 internalYear = 1 551 552 // Offsets to convert between internal and absolute or Unix times. 553 absoluteToInternal int64 = -(absoluteYears*365.2425 + marchThruDecember) * secondsPerDay 554 internalToAbsolute = -absoluteToInternal 555 556 unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay 557 internalToUnix int64 = -unixToInternal 558 559 absoluteToUnix = absoluteToInternal + internalToUnix 560 unixToAbsolute = unixToInternal + internalToAbsolute 561 562 wallToInternal int64 = (1884*365 + 1884/4 - 1884/100 + 1884/400) * secondsPerDay 563 ) 564 565 // An absSeconds counts the number of seconds since the absolute zero instant. 566 type absSeconds uint64 567 568 // An absDays counts the number of days since the absolute zero instant. 569 type absDays uint64 570 571 // An absCentury counts the number of centuries since the absolute zero instant. 572 type absCentury uint64 573 574 // An absCyear counts the number of years since the start of a century. 575 type absCyear int 576 577 // An absYday counts the number of days since the start of a year. 578 // Note that absolute years start on March 1. 579 type absYday int 580 581 // An absMonth counts the number of months since the start of a year. 582 // absMonth=0 denotes March. 583 type absMonth int 584 585 // An absLeap is a single bit (0 or 1) denoting whether a given year is a leap year. 586 type absLeap int 587 588 // An absJanFeb is a single bit (0 or 1) denoting whether a given day falls in January or February. 589 // That is a special case because the absolute years start in March (unlike normal calendar years). 590 type absJanFeb int 591 592 // dateToAbsDays takes a standard year/month/day and returns the 593 // number of days from the absolute epoch to that day. 594 // The days argument can be out of range and in particular can be negative. 595 func dateToAbsDays(year int64, month Month, day int) absDays { 596 // See “Computations on Times” comment above. 597 amonth := uint32(month) 598 janFeb := uint32(0) 599 if amonth < 3 { 600 janFeb = 1 601 } 602 amonth += 12 * janFeb 603 y := uint64(year) - uint64(janFeb) + absoluteYears 604 605 // For amonth is in the range [3,14], we want: 606 // 607 // ayday := (153*amonth - 457) / 5 608 // 609 // (See the “Computations on Times” comment above 610 // as well as Neri and Schneider, section 7.) 611 // 612 // That is equivalent to: 613 // 614 // ayday := (979*amonth - 2919) >> 5 615 // 616 // and the latter form uses a couple fewer instructions, 617 // so use it, saving a few cycles. 618 // See Neri and Schneider, section 8.3 619 // for more about this optimization. 620 // 621 // (Note that there is no saved division, because the compiler 622 // implements / 5 without division in all cases.) 623 ayday := (979*amonth - 2919) >> 5 624 625 century := y / 100 626 cyear := uint32(y % 100) 627 cday := 1461 * cyear / 4 628 centurydays := 146097 * century / 4 629 630 return absDays(centurydays + uint64(int64(cday+ayday)+int64(day)-1)) 631 } 632 633 // days converts absolute seconds to absolute days. 634 func (abs absSeconds) days() absDays { 635 return absDays(abs / secondsPerDay) 636 } 637 638 // split splits days into century, cyear, ayday. 639 func (days absDays) split() (century absCentury, cyear absCyear, ayday absYday) { 640 // See “Computations on Times” comment above. 641 d := 4*uint64(days) + 3 642 century = absCentury(d / 146097) 643 644 // This should be 645 // cday := uint32(d % 146097) / 4 646 // cd := 4*cday + 3 647 // which is to say 648 // cday := uint32(d % 146097) >> 2 649 // cd := cday<<2 + 3 650 // but of course (x>>2<<2)+3 == x|3, 651 // so do that instead. 652 cd := uint32(d%146097) | 3 653 654 // For cdays in the range [0,146097] (100 years), we want: 655 // 656 // cyear := (4 cdays + 3) / 1461 657 // yday := (4 cdays + 3) % 1461 / 4 658 // 659 // (See the “Computations on Times” comment above 660 // as well as Neri and Schneider, section 7.) 661 // 662 // That is equivalent to: 663 // 664 // cyear := (2939745 cdays) >> 32 665 // yday := (2939745 cdays) & 0xFFFFFFFF / 2939745 / 4 666 // 667 // so do that instead, saving a few cycles. 668 // See Neri and Schneider, section 8.3 669 // for more about this optimization. 670 hi, lo := bits.Mul32(2939745, uint32(cd)) 671 cyear = absCyear(hi) 672 ayday = absYday(lo / 2939745 / 4) 673 return 674 } 675 676 // split splits ayday into absolute month and standard (1-based) day-in-month. 677 func (ayday absYday) split() (m absMonth, mday int) { 678 // See “Computations on Times” comment above. 679 // 680 // For yday in the range [0,366], 681 // 682 // amonth := (5 yday + 461) / 153 683 // mday := (5 yday + 461) % 153 / 5 684 // 685 // is equivalent to: 686 // 687 // amonth = (2141 yday + 197913) >> 16 688 // mday = (2141 yday + 197913) & 0xFFFF / 2141 689 // 690 // so do that instead, saving a few cycles. 691 // See Neri and Schneider, section 8.3. 692 d := 2141*uint32(ayday) + 197913 693 return absMonth(d >> 16), 1 + int((d&0xFFFF)/2141) 694 } 695 696 // janFeb returns 1 if the March 1-based ayday is in January or February, 0 otherwise. 697 func (ayday absYday) janFeb() absJanFeb { 698 // See “Computations on Times” comment above. 699 jf := absJanFeb(0) 700 if ayday >= marchThruDecember { 701 jf = 1 702 } 703 return jf 704 } 705 706 // month returns the standard Month for (m, janFeb) 707 func (m absMonth) month(janFeb absJanFeb) Month { 708 // See “Computations on Times” comment above. 709 return Month(m) - Month(janFeb)*12 710 } 711 712 // leap returns 1 if (century, cyear) is a leap year, 0 otherwise. 713 func (century absCentury) leap(cyear absCyear) absLeap { 714 // See “Computations on Times” comment above. 715 y4ok := 0 716 if cyear%4 == 0 { 717 y4ok = 1 718 } 719 y100ok := 0 720 if cyear != 0 { 721 y100ok = 1 722 } 723 y400ok := 0 724 if century%4 == 0 { 725 y400ok = 1 726 } 727 return absLeap(y4ok & (y100ok | y400ok)) 728 } 729 730 // year returns the standard year for (century, cyear, janFeb). 731 func (century absCentury) year(cyear absCyear, janFeb absJanFeb) int { 732 // See “Computations on Times” comment above. 733 return int(uint64(century)*100-absoluteYears) + int(cyear) + int(janFeb) 734 } 735 736 // yday returns the standard 1-based yday for (ayday, janFeb, leap). 737 func (ayday absYday) yday(janFeb absJanFeb, leap absLeap) int { 738 // See “Computations on Times” comment above. 739 return int(ayday) + (1 + 31 + 28) + int(leap)&^int(janFeb) - 365*int(janFeb) 740 } 741 742 // date converts days into standard year, month, day. 743 func (days absDays) date() (year int, month Month, day int) { 744 century, cyear, ayday := days.split() 745 amonth, day := ayday.split() 746 janFeb := ayday.janFeb() 747 year = century.year(cyear, janFeb) 748 month = amonth.month(janFeb) 749 return 750 } 751 752 // yearYday converts days into the standard year and 1-based yday. 753 func (days absDays) yearYday() (year, yday int) { 754 century, cyear, ayday := days.split() 755 janFeb := ayday.janFeb() 756 year = century.year(cyear, janFeb) 757 yday = ayday.yday(janFeb, century.leap(cyear)) 758 return 759 } 760 761 // absSec returns the time t as an absolute seconds, adjusted by the zone offset. 762 // It is called when computing a presentation property like Month or Hour. 763 // We'd rather call it abs, but there are linknames to abs that make that problematic. 764 // See timeAbs below. 765 func (t Time) absSec() absSeconds { 766 l := t.loc 767 // Avoid function calls when possible. 768 if l == nil || l == &localLoc { 769 l = l.get() 770 } 771 sec := t.unixSec() 772 if l != &utcLoc { 773 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { 774 sec += int64(l.cacheZone.offset) 775 } else { 776 _, offset, _, _, _ := l.lookup(sec) 777 sec += int64(offset) 778 } 779 } 780 return absSeconds(sec + (unixToInternal + internalToAbsolute)) 781 } 782 783 // locabs is a combination of the Zone and abs methods, 784 // extracting both return values from a single zone lookup. 785 func (t Time) locabs() (name string, offset int, abs absSeconds) { 786 l := t.loc 787 if l == nil || l == &localLoc { 788 l = l.get() 789 } 790 // Avoid function call if we hit the local time cache. 791 sec := t.unixSec() 792 if l != &utcLoc { 793 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { 794 name = l.cacheZone.name 795 offset = l.cacheZone.offset 796 } else { 797 name, offset, _, _, _ = l.lookup(sec) 798 } 799 sec += int64(offset) 800 } else { 801 name = "UTC" 802 } 803 abs = absSeconds(sec + (unixToInternal + internalToAbsolute)) 804 return 805 } 806 807 // Date returns the year, month, and day in which t occurs. 808 func (t Time) Date() (year int, month Month, day int) { 809 return t.absSec().days().date() 810 } 811 812 // Year returns the year in which t occurs. 813 func (t Time) Year() int { 814 century, cyear, ayday := t.absSec().days().split() 815 janFeb := ayday.janFeb() 816 return century.year(cyear, janFeb) 817 } 818 819 // Month returns the month of the year specified by t. 820 func (t Time) Month() Month { 821 _, _, ayday := t.absSec().days().split() 822 amonth, _ := ayday.split() 823 return amonth.month(ayday.janFeb()) 824 } 825 826 // Day returns the day of the month specified by t. 827 func (t Time) Day() int { 828 _, _, ayday := t.absSec().days().split() 829 _, day := ayday.split() 830 return day 831 } 832 833 // Weekday returns the day of the week specified by t. 834 func (t Time) Weekday() Weekday { 835 return t.absSec().days().weekday() 836 } 837 838 // weekday returns the day of the week specified by days. 839 func (days absDays) weekday() Weekday { 840 // March 1 of the absolute year, like March 1 of 2000, was a Wednesday. 841 return Weekday((uint64(days) + uint64(Wednesday)) % 7) 842 } 843 844 // ISOWeek returns the ISO 8601 year and week number in which t occurs. 845 // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to 846 // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 847 // of year n+1. 848 func (t Time) ISOWeek() (year, week int) { 849 // According to the rule that the first calendar week of a calendar year is 850 // the week including the first Thursday of that year, and that the last one is 851 // the week immediately preceding the first calendar week of the next calendar year. 852 // See https://www.iso.org/obp/ui#iso:std:iso:8601:-1:ed-1:v1:en:term:3.1.1.23 for details. 853 854 // weeks start with Monday 855 // Monday Tuesday Wednesday Thursday Friday Saturday Sunday 856 // 1 2 3 4 5 6 7 857 // +3 +2 +1 0 -1 -2 -3 858 // the offset to Thursday 859 days := t.absSec().days() 860 thu := days + absDays(Thursday-((days-1).weekday()+1)) 861 year, yday := thu.yearYday() 862 return year, (yday-1)/7 + 1 863 } 864 865 // Clock returns the hour, minute, and second within the day specified by t. 866 func (t Time) Clock() (hour, min, sec int) { 867 return t.absSec().clock() 868 } 869 870 // clock returns the hour, minute, and second within the day specified by abs. 871 func (abs absSeconds) clock() (hour, min, sec int) { 872 sec = int(abs % secondsPerDay) 873 hour = sec / secondsPerHour 874 sec -= hour * secondsPerHour 875 min = sec / secondsPerMinute 876 sec -= min * secondsPerMinute 877 return 878 } 879 880 // Hour returns the hour within the day specified by t, in the range [0, 23]. 881 func (t Time) Hour() int { 882 return int(t.absSec()%secondsPerDay) / secondsPerHour 883 } 884 885 // Minute returns the minute offset within the hour specified by t, in the range [0, 59]. 886 func (t Time) Minute() int { 887 return int(t.absSec()%secondsPerHour) / secondsPerMinute 888 } 889 890 // Second returns the second offset within the minute specified by t, in the range [0, 59]. 891 func (t Time) Second() int { 892 return int(t.absSec() % secondsPerMinute) 893 } 894 895 // Nanosecond returns the nanosecond offset within the second specified by t, 896 // in the range [0, 999999999]. 897 func (t Time) Nanosecond() int { 898 return int(t.nsec()) 899 } 900 901 // YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, 902 // and [1,366] in leap years. 903 func (t Time) YearDay() int { 904 _, yday := t.absSec().days().yearYday() 905 return yday 906 } 907 908 // A Duration represents the elapsed time between two instants 909 // as an int64 nanosecond count. The representation limits the 910 // largest representable duration to approximately 290 years. 911 type Duration int64 912 913 const ( 914 minDuration Duration = -1 << 63 915 maxDuration Duration = 1<<63 - 1 916 ) 917 918 // Common durations. There is no definition for units of Day or larger 919 // to avoid confusion across daylight savings time zone transitions. 920 // 921 // To count the number of units in a [Duration], divide: 922 // 923 // second := time.Second 924 // fmt.Print(int64(second/time.Millisecond)) // prints 1000 925 // 926 // To convert an integer number of units to a Duration, multiply: 927 // 928 // seconds := 10 929 // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s 930 const ( 931 Nanosecond Duration = 1 932 Microsecond = 1000 * Nanosecond 933 Millisecond = 1000 * Microsecond 934 Second = 1000 * Millisecond 935 Minute = 60 * Second 936 Hour = 60 * Minute 937 ) 938 939 // String returns a string representing the duration in the form "72h3m0.5s". 940 // Leading zero units are omitted. As a special case, durations less than one 941 // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure 942 // that the leading digit is non-zero. The zero duration formats as 0s. 943 func (d Duration) String() string { 944 // This is inlinable to take advantage of "function outlining". 945 // Thus, the caller can decide whether a string must be heap allocated. 946 var arr [32]byte 947 n := d.format(&arr) 948 return string(arr[n:]) 949 } 950 951 // format formats the representation of d into the end of buf and 952 // returns the offset of the first character. 953 func (d Duration) format(buf *[32]byte) int { 954 // Largest time is 2540400h10m10.000000000s 955 w := len(buf) 956 957 u := uint64(d) 958 neg := d < 0 959 if neg { 960 u = -u 961 } 962 963 if u < uint64(Second) { 964 // Special case: if duration is smaller than a second, 965 // use smaller units, like 1.2ms 966 var prec int 967 w-- 968 buf[w] = 's' 969 w-- 970 switch { 971 case u == 0: 972 buf[w] = '0' 973 return w 974 case u < uint64(Microsecond): 975 // print nanoseconds 976 prec = 0 977 buf[w] = 'n' 978 case u < uint64(Millisecond): 979 // print microseconds 980 prec = 3 981 // U+00B5 'µ' micro sign == 0xC2 0xB5 982 w-- // Need room for two bytes. 983 copy(buf[w:], "µ") 984 default: 985 // print milliseconds 986 prec = 6 987 buf[w] = 'm' 988 } 989 w, u = fmtFrac(buf[:w], u, prec) 990 w = fmtInt(buf[:w], u) 991 } else { 992 w-- 993 buf[w] = 's' 994 995 w, u = fmtFrac(buf[:w], u, 9) 996 997 // u is now integer seconds 998 w = fmtInt(buf[:w], u%60) 999 u /= 60 1000 1001 // u is now integer minutes 1002 if u > 0 { 1003 w-- 1004 buf[w] = 'm' 1005 w = fmtInt(buf[:w], u%60) 1006 u /= 60 1007 1008 // u is now integer hours 1009 // Stop at hours because days can be different lengths. 1010 if u > 0 { 1011 w-- 1012 buf[w] = 'h' 1013 w = fmtInt(buf[:w], u) 1014 } 1015 } 1016 } 1017 1018 if neg { 1019 w-- 1020 buf[w] = '-' 1021 } 1022 1023 return w 1024 } 1025 1026 // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the 1027 // tail of buf, omitting trailing zeros. It omits the decimal 1028 // point too when the fraction is 0. It returns the index where the 1029 // output bytes begin and the value v/10**prec. 1030 func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) { 1031 // Omit trailing zeros up to and including decimal point. 1032 w := len(buf) 1033 print := false 1034 for i := 0; i < prec; i++ { 1035 digit := v % 10 1036 print = print || digit != 0 1037 if print { 1038 w-- 1039 buf[w] = byte(digit) + '0' 1040 } 1041 v /= 10 1042 } 1043 if print { 1044 w-- 1045 buf[w] = '.' 1046 } 1047 return w, v 1048 } 1049 1050 // fmtInt formats v into the tail of buf. 1051 // It returns the index where the output begins. 1052 func fmtInt(buf []byte, v uint64) int { 1053 w := len(buf) 1054 if v == 0 { 1055 w-- 1056 buf[w] = '0' 1057 } else { 1058 for v > 0 { 1059 w-- 1060 buf[w] = byte(v%10) + '0' 1061 v /= 10 1062 } 1063 } 1064 return w 1065 } 1066 1067 // Nanoseconds returns the duration as an integer nanosecond count. 1068 func (d Duration) Nanoseconds() int64 { return int64(d) } 1069 1070 // Microseconds returns the duration as an integer microsecond count. 1071 func (d Duration) Microseconds() int64 { return int64(d) / 1e3 } 1072 1073 // Milliseconds returns the duration as an integer millisecond count. 1074 func (d Duration) Milliseconds() int64 { return int64(d) / 1e6 } 1075 1076 // These methods return float64 because the dominant 1077 // use case is for printing a floating point number like 1.5s, and 1078 // a truncation to integer would make them not useful in those cases. 1079 // Splitting the integer and fraction ourselves guarantees that 1080 // converting the returned float64 to an integer rounds the same 1081 // way that a pure integer conversion would have, even in cases 1082 // where, say, float64(d.Nanoseconds())/1e9 would have rounded 1083 // differently. 1084 1085 // Seconds returns the duration as a floating point number of seconds. 1086 func (d Duration) Seconds() float64 { 1087 sec := d / Second 1088 nsec := d % Second 1089 return float64(sec) + float64(nsec)/1e9 1090 } 1091 1092 // Minutes returns the duration as a floating point number of minutes. 1093 func (d Duration) Minutes() float64 { 1094 min := d / Minute 1095 nsec := d % Minute 1096 return float64(min) + float64(nsec)/(60*1e9) 1097 } 1098 1099 // Hours returns the duration as a floating point number of hours. 1100 func (d Duration) Hours() float64 { 1101 hour := d / Hour 1102 nsec := d % Hour 1103 return float64(hour) + float64(nsec)/(60*60*1e9) 1104 } 1105 1106 // Truncate returns the result of rounding d toward zero to a multiple of m. 1107 // If m <= 0, Truncate returns d unchanged. 1108 func (d Duration) Truncate(m Duration) Duration { 1109 if m <= 0 { 1110 return d 1111 } 1112 return d - d%m 1113 } 1114 1115 // lessThanHalf reports whether x+x < y but avoids overflow, 1116 // assuming x and y are both positive (Duration is signed). 1117 func lessThanHalf(x, y Duration) bool { 1118 return uint64(x)+uint64(x) < uint64(y) 1119 } 1120 1121 // Round returns the result of rounding d to the nearest multiple of m. 1122 // The rounding behavior for halfway values is to round away from zero. 1123 // If the result exceeds the maximum (or minimum) 1124 // value that can be stored in a [Duration], 1125 // Round returns the maximum (or minimum) duration. 1126 // If m <= 0, Round returns d unchanged. 1127 func (d Duration) Round(m Duration) Duration { 1128 if m <= 0 { 1129 return d 1130 } 1131 r := d % m 1132 if d < 0 { 1133 r = -r 1134 if lessThanHalf(r, m) { 1135 return d + r 1136 } 1137 if d1 := d - m + r; d1 < d { 1138 return d1 1139 } 1140 return minDuration // overflow 1141 } 1142 if lessThanHalf(r, m) { 1143 return d - r 1144 } 1145 if d1 := d + m - r; d1 > d { 1146 return d1 1147 } 1148 return maxDuration // overflow 1149 } 1150 1151 // Abs returns the absolute value of d. 1152 // As a special case, Duration([math.MinInt64]) is converted to Duration([math.MaxInt64]), 1153 // reducing its magnitude by 1 nanosecond. 1154 func (d Duration) Abs() Duration { 1155 switch { 1156 case d >= 0: 1157 return d 1158 case d == minDuration: 1159 return maxDuration 1160 default: 1161 return -d 1162 } 1163 } 1164 1165 // Add returns the time t+d. 1166 func (t Time) Add(d Duration) Time { 1167 dsec := int64(d / 1e9) 1168 nsec := t.nsec() + int32(d%1e9) 1169 if nsec >= 1e9 { 1170 dsec++ 1171 nsec -= 1e9 1172 } else if nsec < 0 { 1173 dsec-- 1174 nsec += 1e9 1175 } 1176 t.wall = t.wall&^nsecMask | uint64(nsec) // update nsec 1177 t.addSec(dsec) 1178 if t.wall&hasMonotonic != 0 { 1179 te := t.ext + int64(d) 1180 if d < 0 && te > t.ext || d > 0 && te < t.ext { 1181 // Monotonic clock reading now out of range; degrade to wall-only. 1182 t.stripMono() 1183 } else { 1184 t.ext = te 1185 } 1186 } 1187 return t 1188 } 1189 1190 // Sub returns the duration t-u. If the result exceeds the maximum (or minimum) 1191 // value that can be stored in a [Duration], the maximum (or minimum) duration 1192 // will be returned. 1193 // To compute t-d for a duration d, use t.Add(-d). 1194 func (t Time) Sub(u Time) Duration { 1195 if t.wall&u.wall&hasMonotonic != 0 { 1196 return subMono(t.ext, u.ext) 1197 } 1198 d := Duration(t.sec()-u.sec())*Second + Duration(t.nsec()-u.nsec()) 1199 // Check for overflow or underflow. 1200 switch { 1201 case u.Add(d).Equal(t): 1202 return d // d is correct 1203 case t.Before(u): 1204 return minDuration // t - u is negative out of range 1205 default: 1206 return maxDuration // t - u is positive out of range 1207 } 1208 } 1209 1210 func subMono(t, u int64) Duration { 1211 d := Duration(t - u) 1212 if d < 0 && t > u { 1213 return maxDuration // t - u is positive out of range 1214 } 1215 if d > 0 && t < u { 1216 return minDuration // t - u is negative out of range 1217 } 1218 return d 1219 } 1220 1221 // Since returns the time elapsed since t. 1222 // It is shorthand for time.Now().Sub(t). 1223 func Since(t Time) Duration { 1224 if t.wall&hasMonotonic != 0 { 1225 // Common case optimization: if t has monotonic time, then Sub will use only it. 1226 return subMono(runtimeNano()-startNano, t.ext) 1227 } 1228 return Now().Sub(t) 1229 } 1230 1231 // Until returns the duration until t. 1232 // It is shorthand for t.Sub(time.Now()). 1233 func Until(t Time) Duration { 1234 if t.wall&hasMonotonic != 0 { 1235 // Common case optimization: if t has monotonic time, then Sub will use only it. 1236 return subMono(t.ext, runtimeNano()-startNano) 1237 } 1238 return t.Sub(Now()) 1239 } 1240 1241 // AddDate returns the time corresponding to adding the 1242 // given number of years, months, and days to t. 1243 // For example, AddDate(-1, 2, 3) applied to January 1, 2011 1244 // returns March 4, 2010. 1245 // 1246 // Note that dates are fundamentally coupled to timezones, and calendrical 1247 // periods like days don't have fixed durations. AddDate uses the Location of 1248 // the Time value to determine these durations. That means that the same 1249 // AddDate arguments can produce a different shift in absolute time depending on 1250 // the base Time value and its Location. For example, AddDate(0, 0, 1) applied 1251 // to 12:00 on March 27 always returns 12:00 on March 28. At some locations and 1252 // in some years this is a 24 hour shift. In others it's a 23 hour shift due to 1253 // daylight savings time transitions. 1254 // 1255 // AddDate normalizes its result in the same way that Date does, 1256 // so, for example, adding one month to October 31 yields 1257 // December 1, the normalized form for November 31. 1258 func (t Time) AddDate(years int, months int, days int) Time { 1259 year, month, day := t.Date() 1260 hour, min, sec := t.Clock() 1261 return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec()), t.Location()) 1262 } 1263 1264 // daysBefore returns the number of days in a non-leap year before month m. 1265 // daysBefore(December+1) returns 365. 1266 func daysBefore(m Month) int { 1267 adj := 0 1268 if m >= March { 1269 adj = -2 1270 } 1271 1272 // With the -2 adjustment after February, 1273 // we need to compute the running sum of: 1274 // 0 31 30 31 30 31 30 31 31 30 31 30 31 1275 // which is: 1276 // 0 31 61 92 122 153 183 214 245 275 306 336 367 1277 // This is almost exactly 367/12×(m-1) except for the 1278 // occasonal off-by-one suggesting there may be an 1279 // integer approximation of the form (a×m + b)/c. 1280 // A brute force search over small a, b, c finds that 1281 // (214×m - 211) / 7 computes the function perfectly. 1282 return (214*int(m)-211)/7 + adj 1283 } 1284 1285 func daysIn(m Month, year int) int { 1286 if m == February { 1287 if isLeap(year) { 1288 return 29 1289 } 1290 return 28 1291 } 1292 // With the special case of February eliminated, the pattern is 1293 // 31 30 31 30 31 30 31 31 30 31 30 31 1294 // Adding m&1 produces the basic alternation; 1295 // adding (m>>3)&1 inverts the alternation starting in August. 1296 return 30 + int((m+m>>3)&1) 1297 } 1298 1299 // Provided by package runtime. 1300 func now() (sec int64, nsec int32, mono int64) 1301 1302 // runtimeNano returns the current value of the runtime clock in nanoseconds. 1303 // 1304 //go:linkname runtimeNano runtime.nanotime 1305 func runtimeNano() int64 1306 1307 // Monotonic times are reported as offsets from startNano. 1308 // We initialize startNano to runtimeNano() - 1 so that on systems where 1309 // monotonic time resolution is fairly low (e.g. Windows 2008 1310 // which appears to have a default resolution of 15ms), 1311 // we avoid ever reporting a monotonic time of 0. 1312 // (Callers may want to use 0 as "time not set".) 1313 var startNano int64 = runtimeNano() - 1 1314 1315 // x/tools uses a linkname of time.Now in its tests. No harm done. 1316 //go:linkname Now 1317 1318 // Now returns the current local time. 1319 func Now() Time { 1320 sec, nsec, mono := now() 1321 mono -= startNano 1322 sec += unixToInternal - minWall 1323 if uint64(sec)>>33 != 0 { 1324 // Seconds field overflowed the 33 bits available when 1325 // storing a monotonic time. This will be true after 1326 // March 16, 2157. 1327 return Time{uint64(nsec), sec + minWall, Local} 1328 } 1329 return Time{hasMonotonic | uint64(sec)<<nsecShift | uint64(nsec), mono, Local} 1330 } 1331 1332 func unixTime(sec int64, nsec int32) Time { 1333 return Time{uint64(nsec), sec + unixToInternal, Local} 1334 } 1335 1336 // UTC returns t with the location set to UTC. 1337 func (t Time) UTC() Time { 1338 t.setLoc(&utcLoc) 1339 return t 1340 } 1341 1342 // Local returns t with the location set to local time. 1343 func (t Time) Local() Time { 1344 t.setLoc(Local) 1345 return t 1346 } 1347 1348 // In returns a copy of t representing the same time instant, but 1349 // with the copy's location information set to loc for display 1350 // purposes. 1351 // 1352 // In panics if loc is nil. 1353 func (t Time) In(loc *Location) Time { 1354 if loc == nil { 1355 panic("time: missing Location in call to Time.In") 1356 } 1357 t.setLoc(loc) 1358 return t 1359 } 1360 1361 // Location returns the time zone information associated with t. 1362 func (t Time) Location() *Location { 1363 l := t.loc 1364 if l == nil { 1365 l = UTC 1366 } 1367 return l 1368 } 1369 1370 // Zone computes the time zone in effect at time t, returning the abbreviated 1371 // name of the zone (such as "CET") and its offset in seconds east of UTC. 1372 func (t Time) Zone() (name string, offset int) { 1373 name, offset, _, _, _ = t.loc.lookup(t.unixSec()) 1374 return 1375 } 1376 1377 // ZoneBounds returns the bounds of the time zone in effect at time t. 1378 // The zone begins at start and the next zone begins at end. 1379 // If the zone begins at the beginning of time, start will be returned as a zero Time. 1380 // If the zone goes on forever, end will be returned as a zero Time. 1381 // The Location of the returned times will be the same as t. 1382 func (t Time) ZoneBounds() (start, end Time) { 1383 _, _, startSec, endSec, _ := t.loc.lookup(t.unixSec()) 1384 if startSec != alpha { 1385 start = unixTime(startSec, 0) 1386 start.setLoc(t.loc) 1387 } 1388 if endSec != omega { 1389 end = unixTime(endSec, 0) 1390 end.setLoc(t.loc) 1391 } 1392 return 1393 } 1394 1395 // Unix returns t as a Unix time, the number of seconds elapsed 1396 // since January 1, 1970 UTC. The result does not depend on the 1397 // location associated with t. 1398 // Unix-like operating systems often record time as a 32-bit 1399 // count of seconds, but since the method here returns a 64-bit 1400 // value it is valid for billions of years into the past or future. 1401 func (t Time) Unix() int64 { 1402 return t.unixSec() 1403 } 1404 1405 // UnixMilli returns t as a Unix time, the number of milliseconds elapsed since 1406 // January 1, 1970 UTC. The result is undefined if the Unix time in 1407 // milliseconds cannot be represented by an int64 (a date more than 292 million 1408 // years before or after 1970). The result does not depend on the 1409 // location associated with t. 1410 func (t Time) UnixMilli() int64 { 1411 return t.unixSec()*1e3 + int64(t.nsec())/1e6 1412 } 1413 1414 // UnixMicro returns t as a Unix time, the number of microseconds elapsed since 1415 // January 1, 1970 UTC. The result is undefined if the Unix time in 1416 // microseconds cannot be represented by an int64 (a date before year -290307 or 1417 // after year 294246). The result does not depend on the location associated 1418 // with t. 1419 func (t Time) UnixMicro() int64 { 1420 return t.unixSec()*1e6 + int64(t.nsec())/1e3 1421 } 1422 1423 // UnixNano returns t as a Unix time, the number of nanoseconds elapsed 1424 // since January 1, 1970 UTC. The result is undefined if the Unix time 1425 // in nanoseconds cannot be represented by an int64 (a date before the year 1426 // 1678 or after 2262). Note that this means the result of calling UnixNano 1427 // on the zero Time is undefined. The result does not depend on the 1428 // location associated with t. 1429 func (t Time) UnixNano() int64 { 1430 return (t.unixSec())*1e9 + int64(t.nsec()) 1431 } 1432 1433 const ( 1434 timeBinaryVersionV1 byte = iota + 1 // For general situation 1435 timeBinaryVersionV2 // For LMT only 1436 ) 1437 1438 // AppendBinary implements the [encoding.BinaryAppender] interface. 1439 func (t Time) AppendBinary(b []byte) ([]byte, error) { 1440 var offsetMin int16 // minutes east of UTC. -1 is UTC. 1441 var offsetSec int8 1442 version := timeBinaryVersionV1 1443 1444 if t.Location() == UTC { 1445 offsetMin = -1 1446 } else { 1447 _, offset := t.Zone() 1448 if offset%60 != 0 { 1449 version = timeBinaryVersionV2 1450 offsetSec = int8(offset % 60) 1451 } 1452 1453 offset /= 60 1454 if offset < -32768 || offset == -1 || offset > 32767 { 1455 return b, errors.New("Time.MarshalBinary: unexpected zone offset") 1456 } 1457 offsetMin = int16(offset) 1458 } 1459 1460 sec := t.sec() 1461 nsec := t.nsec() 1462 b = append(b, 1463 version, // byte 0 : version 1464 byte(sec>>56), // bytes 1-8: seconds 1465 byte(sec>>48), 1466 byte(sec>>40), 1467 byte(sec>>32), 1468 byte(sec>>24), 1469 byte(sec>>16), 1470 byte(sec>>8), 1471 byte(sec), 1472 byte(nsec>>24), // bytes 9-12: nanoseconds 1473 byte(nsec>>16), 1474 byte(nsec>>8), 1475 byte(nsec), 1476 byte(offsetMin>>8), // bytes 13-14: zone offset in minutes 1477 byte(offsetMin), 1478 ) 1479 if version == timeBinaryVersionV2 { 1480 b = append(b, byte(offsetSec)) 1481 } 1482 return b, nil 1483 } 1484 1485 // MarshalBinary implements the [encoding.BinaryMarshaler] interface. 1486 func (t Time) MarshalBinary() ([]byte, error) { 1487 b, err := t.AppendBinary(make([]byte, 0, 16)) 1488 if err != nil { 1489 return nil, err 1490 } 1491 return b, nil 1492 } 1493 1494 // UnmarshalBinary implements the [encoding.BinaryUnmarshaler] interface. 1495 func (t *Time) UnmarshalBinary(data []byte) error { 1496 buf := data 1497 if len(buf) == 0 { 1498 return errors.New("Time.UnmarshalBinary: no data") 1499 } 1500 1501 version := buf[0] 1502 if version != timeBinaryVersionV1 && version != timeBinaryVersionV2 { 1503 return errors.New("Time.UnmarshalBinary: unsupported version") 1504 } 1505 1506 wantLen := /*version*/ 1 + /*sec*/ 8 + /*nsec*/ 4 + /*zone offset*/ 2 1507 if version == timeBinaryVersionV2 { 1508 wantLen++ 1509 } 1510 if len(buf) != wantLen { 1511 return errors.New("Time.UnmarshalBinary: invalid length") 1512 } 1513 1514 buf = buf[1:] 1515 sec := int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 | 1516 int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56 1517 1518 buf = buf[8:] 1519 nsec := int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24 1520 1521 buf = buf[4:] 1522 offset := int(int16(buf[1])|int16(buf[0])<<8) * 60 1523 if version == timeBinaryVersionV2 { 1524 offset += int(buf[2]) 1525 } 1526 1527 *t = Time{} 1528 t.wall = uint64(nsec) 1529 t.ext = sec 1530 1531 if offset == -1*60 { 1532 t.setLoc(&utcLoc) 1533 } else if _, localoff, _, _, _ := Local.lookup(t.unixSec()); offset == localoff { 1534 t.setLoc(Local) 1535 } else { 1536 t.setLoc(FixedZone("", offset)) 1537 } 1538 1539 return nil 1540 } 1541 1542 // TODO(rsc): Remove GobEncoder, GobDecoder, MarshalJSON, UnmarshalJSON in Go 2. 1543 // The same semantics will be provided by the generic MarshalBinary, MarshalText, 1544 // UnmarshalBinary, UnmarshalText. 1545 1546 // GobEncode implements the gob.GobEncoder interface. 1547 func (t Time) GobEncode() ([]byte, error) { 1548 return t.MarshalBinary() 1549 } 1550 1551 // GobDecode implements the gob.GobDecoder interface. 1552 func (t *Time) GobDecode(data []byte) error { 1553 return t.UnmarshalBinary(data) 1554 } 1555 1556 // MarshalJSON implements the [encoding/json.Marshaler] interface. 1557 // The time is a quoted string in the RFC 3339 format with sub-second precision. 1558 // If the timestamp cannot be represented as valid RFC 3339 1559 // (e.g., the year is out of range), then an error is reported. 1560 func (t Time) MarshalJSON() ([]byte, error) { 1561 b := make([]byte, 0, len(RFC3339Nano)+len(`""`)) 1562 b = append(b, '"') 1563 b, err := t.appendStrictRFC3339(b) 1564 b = append(b, '"') 1565 if err != nil { 1566 return nil, errors.New("Time.MarshalJSON: " + err.Error()) 1567 } 1568 return b, nil 1569 } 1570 1571 // UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. 1572 // The time must be a quoted string in the RFC 3339 format. 1573 func (t *Time) UnmarshalJSON(data []byte) error { 1574 if string(data) == "null" { 1575 return nil 1576 } 1577 // TODO(https://go.dev/issue/47353): Properly unescape a JSON string. 1578 if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { 1579 return errors.New("Time.UnmarshalJSON: input is not a JSON string") 1580 } 1581 data = data[len(`"`) : len(data)-len(`"`)] 1582 var err error 1583 *t, err = parseStrictRFC3339(data) 1584 return err 1585 } 1586 1587 func (t Time) appendTo(b []byte, errPrefix string) ([]byte, error) { 1588 b, err := t.appendStrictRFC3339(b) 1589 if err != nil { 1590 return nil, errors.New(errPrefix + err.Error()) 1591 } 1592 return b, nil 1593 } 1594 1595 // AppendText implements the [encoding.TextAppender] interface. 1596 // The time is formatted in RFC 3339 format with sub-second precision. 1597 // If the timestamp cannot be represented as valid RFC 3339 1598 // (e.g., the year is out of range), then an error is returned. 1599 func (t Time) AppendText(b []byte) ([]byte, error) { 1600 return t.appendTo(b, "Time.AppendText: ") 1601 } 1602 1603 // MarshalText implements the [encoding.TextMarshaler] interface. The output 1604 // matches that of calling the [Time.AppendText] method. 1605 // 1606 // See [Time.AppendText] for more information. 1607 func (t Time) MarshalText() ([]byte, error) { 1608 return t.appendTo(make([]byte, 0, len(RFC3339Nano)), "Time.MarshalText: ") 1609 } 1610 1611 // UnmarshalText implements the [encoding.TextUnmarshaler] interface. 1612 // The time must be in the RFC 3339 format. 1613 func (t *Time) UnmarshalText(data []byte) error { 1614 var err error 1615 *t, err = parseStrictRFC3339(data) 1616 return err 1617 } 1618 1619 // Unix returns the local Time corresponding to the given Unix time, 1620 // sec seconds and nsec nanoseconds since January 1, 1970 UTC. 1621 // It is valid to pass nsec outside the range [0, 999999999]. 1622 // Not all sec values have a corresponding time value. One such 1623 // value is 1<<63-1 (the largest int64 value). 1624 func Unix(sec int64, nsec int64) Time { 1625 if nsec < 0 || nsec >= 1e9 { 1626 n := nsec / 1e9 1627 sec += n 1628 nsec -= n * 1e9 1629 if nsec < 0 { 1630 nsec += 1e9 1631 sec-- 1632 } 1633 } 1634 return unixTime(sec, int32(nsec)) 1635 } 1636 1637 // UnixMilli returns the local Time corresponding to the given Unix time, 1638 // msec milliseconds since January 1, 1970 UTC. 1639 func UnixMilli(msec int64) Time { 1640 return Unix(msec/1e3, (msec%1e3)*1e6) 1641 } 1642 1643 // UnixMicro returns the local Time corresponding to the given Unix time, 1644 // usec microseconds since January 1, 1970 UTC. 1645 func UnixMicro(usec int64) Time { 1646 return Unix(usec/1e6, (usec%1e6)*1e3) 1647 } 1648 1649 // IsDST reports whether the time in the configured location is in Daylight Savings Time. 1650 func (t Time) IsDST() bool { 1651 _, _, _, _, isDST := t.loc.lookup(t.Unix()) 1652 return isDST 1653 } 1654 1655 func isLeap(year int) bool { 1656 // year%4 == 0 && (year%100 != 0 || year%400 == 0) 1657 // Bottom 2 bits must be clear. 1658 // For multiples of 25, bottom 4 bits must be clear. 1659 // Thanks to Cassio Neri for this trick. 1660 mask := 0xf 1661 if year%25 != 0 { 1662 mask = 3 1663 } 1664 return year&mask == 0 1665 } 1666 1667 // norm returns nhi, nlo such that 1668 // 1669 // hi * base + lo == nhi * base + nlo 1670 // 0 <= nlo < base 1671 func norm(hi, lo, base int) (nhi, nlo int) { 1672 if lo < 0 { 1673 n := (-lo-1)/base + 1 1674 hi -= n 1675 lo += n * base 1676 } 1677 if lo >= base { 1678 n := lo / base 1679 hi += n 1680 lo -= n * base 1681 } 1682 return hi, lo 1683 } 1684 1685 // Date returns the Time corresponding to 1686 // 1687 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds 1688 // 1689 // in the appropriate zone for that time in the given location. 1690 // 1691 // The month, day, hour, min, sec, and nsec values may be outside 1692 // their usual ranges and will be normalized during the conversion. 1693 // For example, October 32 converts to November 1. 1694 // 1695 // A daylight savings time transition skips or repeats times. 1696 // For example, in the United States, March 13, 2011 2:15am never occurred, 1697 // while November 6, 2011 1:15am occurred twice. In such cases, the 1698 // choice of time zone, and therefore the time, is not well-defined. 1699 // Date returns a time that is correct in one of the two zones involved 1700 // in the transition, but it does not guarantee which. 1701 // 1702 // Date panics if loc is nil. 1703 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time { 1704 if loc == nil { 1705 panic("time: missing Location in call to Date") 1706 } 1707 1708 // Normalize month, overflowing into year. 1709 m := int(month) - 1 1710 year, m = norm(year, m, 12) 1711 month = Month(m) + 1 1712 1713 // Normalize nsec, sec, min, hour, overflowing into day. 1714 sec, nsec = norm(sec, nsec, 1e9) 1715 min, sec = norm(min, sec, 60) 1716 hour, min = norm(hour, min, 60) 1717 day, hour = norm(day, hour, 24) 1718 1719 // Convert to absolute time and then Unix time. 1720 unix := int64(dateToAbsDays(int64(year), month, day))*secondsPerDay + 1721 int64(hour*secondsPerHour+min*secondsPerMinute+sec) + 1722 absoluteToUnix 1723 1724 // Look for zone offset for expected time, so we can adjust to UTC. 1725 // The lookup function expects UTC, so first we pass unix in the 1726 // hope that it will not be too close to a zone transition, 1727 // and then adjust if it is. 1728 _, offset, start, end, _ := loc.lookup(unix) 1729 if offset != 0 { 1730 utc := unix - int64(offset) 1731 // If utc is valid for the time zone we found, then we have the right offset. 1732 // If not, we get the correct offset by looking up utc in the location. 1733 if utc < start || utc >= end { 1734 _, offset, _, _, _ = loc.lookup(utc) 1735 } 1736 unix -= int64(offset) 1737 } 1738 1739 t := unixTime(unix, int32(nsec)) 1740 t.setLoc(loc) 1741 return t 1742 } 1743 1744 // Truncate returns the result of rounding t down to a multiple of d (since the zero time). 1745 // If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. 1746 // 1747 // Truncate operates on the time as an absolute duration since the 1748 // zero time; it does not operate on the presentation form of the 1749 // time. Thus, Truncate(Hour) may return a time with a non-zero 1750 // minute, depending on the time's Location. 1751 func (t Time) Truncate(d Duration) Time { 1752 t.stripMono() 1753 if d <= 0 { 1754 return t 1755 } 1756 _, r := div(t, d) 1757 return t.Add(-r) 1758 } 1759 1760 // Round returns the result of rounding t to the nearest multiple of d (since the zero time). 1761 // The rounding behavior for halfway values is to round up. 1762 // If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. 1763 // 1764 // Round operates on the time as an absolute duration since the 1765 // zero time; it does not operate on the presentation form of the 1766 // time. Thus, Round(Hour) may return a time with a non-zero 1767 // minute, depending on the time's Location. 1768 func (t Time) Round(d Duration) Time { 1769 t.stripMono() 1770 if d <= 0 { 1771 return t 1772 } 1773 _, r := div(t, d) 1774 if lessThanHalf(r, d) { 1775 return t.Add(-r) 1776 } 1777 return t.Add(d - r) 1778 } 1779 1780 // div divides t by d and returns the quotient parity and remainder. 1781 // We don't use the quotient parity anymore (round half up instead of round to even) 1782 // but it's still here in case we change our minds. 1783 func div(t Time, d Duration) (qmod2 int, r Duration) { 1784 neg := false 1785 nsec := t.nsec() 1786 sec := t.sec() 1787 if sec < 0 { 1788 // Operate on absolute value. 1789 neg = true 1790 sec = -sec 1791 nsec = -nsec 1792 if nsec < 0 { 1793 nsec += 1e9 1794 sec-- // sec >= 1 before the -- so safe 1795 } 1796 } 1797 1798 switch { 1799 // Special case: 2d divides 1 second. 1800 case d < Second && Second%(d+d) == 0: 1801 qmod2 = int(nsec/int32(d)) & 1 1802 r = Duration(nsec % int32(d)) 1803 1804 // Special case: d is a multiple of 1 second. 1805 case d%Second == 0: 1806 d1 := int64(d / Second) 1807 qmod2 = int(sec/d1) & 1 1808 r = Duration(sec%d1)*Second + Duration(nsec) 1809 1810 // General case. 1811 // This could be faster if more cleverness were applied, 1812 // but it's really only here to avoid special case restrictions in the API. 1813 // No one will care about these cases. 1814 default: 1815 // Compute nanoseconds as 128-bit number. 1816 sec := uint64(sec) 1817 tmp := (sec >> 32) * 1e9 1818 u1 := tmp >> 32 1819 u0 := tmp << 32 1820 tmp = (sec & 0xFFFFFFFF) * 1e9 1821 u0x, u0 := u0, u0+tmp 1822 if u0 < u0x { 1823 u1++ 1824 } 1825 u0x, u0 = u0, u0+uint64(nsec) 1826 if u0 < u0x { 1827 u1++ 1828 } 1829 1830 // Compute remainder by subtracting r<<k for decreasing k. 1831 // Quotient parity is whether we subtract on last round. 1832 d1 := uint64(d) 1833 for d1>>63 != 1 { 1834 d1 <<= 1 1835 } 1836 d0 := uint64(0) 1837 for { 1838 qmod2 = 0 1839 if u1 > d1 || u1 == d1 && u0 >= d0 { 1840 // subtract 1841 qmod2 = 1 1842 u0x, u0 = u0, u0-d0 1843 if u0 > u0x { 1844 u1-- 1845 } 1846 u1 -= d1 1847 } 1848 if d1 == 0 && d0 == uint64(d) { 1849 break 1850 } 1851 d0 >>= 1 1852 d0 |= (d1 & 1) << 63 1853 d1 >>= 1 1854 } 1855 r = Duration(u0) 1856 } 1857 1858 if neg && r != 0 { 1859 // If input was negative and not an exact multiple of d, we computed q, r such that 1860 // q*d + r = -t 1861 // But the right answers are given by -(q-1), d-r: 1862 // q*d + r = -t 1863 // -q*d - r = t 1864 // -(q-1)*d + (d - r) = t 1865 qmod2 ^= 1 1866 r = d - r 1867 } 1868 return 1869 } 1870 1871 // Regrettable Linkname Compatibility 1872 // 1873 // timeAbs, absDate, and absClock mimic old internal details, no longer used. 1874 // Widely used packages linknamed these to get “faster” time routines. 1875 // Notable members of the hall of shame include: 1876 // - gitee.com/quant1x/gox 1877 // - github.com/phuslu/log 1878 // 1879 // phuslu hard-coded 'Unix time + 9223372028715321600' [sic] 1880 // as the input to absDate and absClock, using the old Jan 1-based 1881 // absolute times. 1882 // quant1x linknamed the time.Time.abs method and passed the 1883 // result of that method to absDate and absClock. 1884 // 1885 // Keeping both of these working forces us to provide these three 1886 // routines here, operating on the old Jan 1-based epoch instead 1887 // of the new March 1-based epoch. And the fact that time.Time.abs 1888 // was linknamed means that we have to call the current abs method 1889 // something different (time.Time.absSec, defined above) to make it 1890 // possible to provide this simulation of the old routines here. 1891 // 1892 // None of this code is linked into the binary if not referenced by 1893 // these linkname-happy packages. In particular, despite its name, 1894 // time.Time.abs does not appear in the time.Time method table. 1895 // 1896 // Do not remove these routines or their linknames, or change the 1897 // type signature or meaning of arguments. 1898 1899 //go:linkname legacyTimeTimeAbs time.Time.abs 1900 func legacyTimeTimeAbs(t Time) uint64 { 1901 return uint64(t.absSec() - marchThruDecember*secondsPerDay) 1902 } 1903 1904 //go:linkname legacyAbsClock time.absClock 1905 func legacyAbsClock(abs uint64) (hour, min, sec int) { 1906 return absSeconds(abs + marchThruDecember*secondsPerDay).clock() 1907 } 1908 1909 //go:linkname legacyAbsDate time.absDate 1910 func legacyAbsDate(abs uint64, full bool) (year int, month Month, day int, yday int) { 1911 d := absSeconds(abs + marchThruDecember*secondsPerDay).days() 1912 year, month, day = d.date() 1913 _, yday = d.yearYday() 1914 yday-- // yearYday is 1-based, old API was 0-based 1915 return 1916 } 1917