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 := []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 := []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 []byte, 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 && !runtimeIsBubbled() {
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 && !runtimeIsBubbled() {
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 //
1301 // now returns the current real time, and is superseded by runtimeNow which returns
1302 // the fake synctest clock when appropriate.
1303 //
1304 // now should be an internal detail,
1305 // but widely used packages access it using linkname.
1306 // Notable members of the hall of shame include:
1307 // - gitee.com/quant1x/gox
1308 // - github.com/phuslu/log
1309 // - github.com/sethvargo/go-limiter
1310 // - github.com/ulule/limiter/v3
1311 //
1312 // Do not remove or change the type signature.
1313 // See go.dev/issue/67401.
1314 func now() (sec int64, nsec int32, mono int64)
1315 1316 // runtimeNow returns the current time.
1317 // When called within a synctest.Run bubble, it returns the group's fake clock.
1318 //
1319 //go:linkname runtimeNow
1320 func runtimeNow() (sec int64, nsec int32, mono int64)
1321 1322 // runtimeNano returns the current value of the runtime clock in nanoseconds.
1323 // When called within a synctest.Run bubble, it returns the group's fake clock.
1324 //
1325 //go:linkname runtimeNano
1326 func runtimeNano() int64
1327 1328 //go:linkname runtimeIsBubbled
1329 func runtimeIsBubbled() bool
1330 1331 // Monotonic times are reported as offsets from startNano.
1332 // We initialize startNano to runtimeNano() - 1 so that on systems where
1333 // monotonic time resolution is fairly low (e.g. Windows 2008
1334 // which appears to have a default resolution of 15ms),
1335 // we avoid ever reporting a monotonic time of 0.
1336 // (Callers may want to use 0 as "time not set".)
1337 var startNano int64 = runtimeNano() - 1
1338 1339 // x/tools uses a linkname of time.Now in its tests. No harm done.
1340 //go:linkname Now
1341 1342 // Now returns the current local time.
1343 func Now() Time {
1344 sec, nsec, mono := runtimeNow()
1345 if mono == 0 {
1346 return Time{uint64(nsec), sec + unixToInternal, Local}
1347 }
1348 mono -= startNano
1349 sec += unixToInternal - minWall
1350 if uint64(sec)>>33 != 0 {
1351 // Seconds field overflowed the 33 bits available when
1352 // storing a monotonic time. This will be true after
1353 // March 16, 2157.
1354 return Time{uint64(nsec), sec + minWall, Local}
1355 }
1356 return Time{hasMonotonic | uint64(sec)<<nsecShift | uint64(nsec), mono, Local}
1357 }
1358 1359 func unixTime(sec int64, nsec int32) Time {
1360 return Time{uint64(nsec), sec + unixToInternal, Local}
1361 }
1362 1363 // UTC returns t with the location set to UTC.
1364 func (t Time) UTC() Time {
1365 t.setLoc(&utcLoc)
1366 return t
1367 }
1368 1369 // Local returns t with the location set to local time.
1370 func (t Time) Local() Time {
1371 t.setLoc(Local)
1372 return t
1373 }
1374 1375 // In returns a copy of t representing the same time instant, but
1376 // with the copy's location information set to loc for display
1377 // purposes.
1378 //
1379 // In panics if loc is nil.
1380 func (t Time) In(loc *Location) Time {
1381 if loc == nil {
1382 panic("time: missing Location in call to Time.In")
1383 }
1384 t.setLoc(loc)
1385 return t
1386 }
1387 1388 // Location returns the time zone information associated with t.
1389 func (t Time) Location() *Location {
1390 l := t.loc
1391 if l == nil {
1392 l = UTC
1393 }
1394 return l
1395 }
1396 1397 // Zone computes the time zone in effect at time t, returning the abbreviated
1398 // name of the zone (such as "CET") and its offset in seconds east of UTC.
1399 func (t Time) Zone() (name []byte, offset int) {
1400 name, offset, _, _, _ = t.loc.lookup(t.unixSec())
1401 return
1402 }
1403 1404 // ZoneBounds returns the bounds of the time zone in effect at time t.
1405 // The zone begins at start and the next zone begins at end.
1406 // If the zone begins at the beginning of time, start will be returned as a zero Time.
1407 // If the zone goes on forever, end will be returned as a zero Time.
1408 // The Location of the returned times will be the same as t.
1409 func (t Time) ZoneBounds() (start, end Time) {
1410 _, _, startSec, endSec, _ := t.loc.lookup(t.unixSec())
1411 if startSec != alpha {
1412 start = unixTime(startSec, 0)
1413 start.setLoc(t.loc)
1414 }
1415 if endSec != omega {
1416 end = unixTime(endSec, 0)
1417 end.setLoc(t.loc)
1418 }
1419 return
1420 }
1421 1422 // Unix returns t as a Unix time, the number of seconds elapsed
1423 // since January 1, 1970 UTC. The result does not depend on the
1424 // location associated with t.
1425 // Unix-like operating systems often record time as a 32-bit
1426 // count of seconds, but since the method here returns a 64-bit
1427 // value it is valid for billions of years into the past or future.
1428 func (t Time) Unix() int64 {
1429 return t.unixSec()
1430 }
1431 1432 // UnixMilli returns t as a Unix time, the number of milliseconds elapsed since
1433 // January 1, 1970 UTC. The result is undefined if the Unix time in
1434 // milliseconds cannot be represented by an int64 (a date more than 292 million
1435 // years before or after 1970). The result does not depend on the
1436 // location associated with t.
1437 func (t Time) UnixMilli() int64 {
1438 return t.unixSec()*1e3 + int64(t.nsec())/1e6
1439 }
1440 1441 // UnixMicro returns t as a Unix time, the number of microseconds elapsed since
1442 // January 1, 1970 UTC. The result is undefined if the Unix time in
1443 // microseconds cannot be represented by an int64 (a date before year -290307 or
1444 // after year 294246). The result does not depend on the location associated
1445 // with t.
1446 func (t Time) UnixMicro() int64 {
1447 return t.unixSec()*1e6 + int64(t.nsec())/1e3
1448 }
1449 1450 // UnixNano returns t as a Unix time, the number of nanoseconds elapsed
1451 // since January 1, 1970 UTC. The result is undefined if the Unix time
1452 // in nanoseconds cannot be represented by an int64 (a date before the year
1453 // 1678 or after 2262). Note that this means the result of calling UnixNano
1454 // on the zero Time is undefined. The result does not depend on the
1455 // location associated with t.
1456 func (t Time) UnixNano() int64 {
1457 return (t.unixSec())*1e9 + int64(t.nsec())
1458 }
1459 1460 const (
1461 timeBinaryVersionV1 byte = iota + 1 // For general situation
1462 timeBinaryVersionV2 // For LMT only
1463 )
1464 1465 // AppendBinary implements the [encoding.BinaryAppender] interface.
1466 func (t Time) AppendBinary(b []byte) ([]byte, error) {
1467 var offsetMin int16 // minutes east of UTC. -1 is UTC.
1468 var offsetSec int8
1469 version := timeBinaryVersionV1
1470 1471 if t.Location() == UTC {
1472 offsetMin = -1
1473 } else {
1474 _, offset := t.Zone()
1475 if offset%60 != 0 {
1476 version = timeBinaryVersionV2
1477 offsetSec = int8(offset % 60)
1478 }
1479 1480 offset /= 60
1481 if offset < -32768 || offset == -1 || offset > 32767 {
1482 return b, errors.New("Time.MarshalBinary: unexpected zone offset")
1483 }
1484 offsetMin = int16(offset)
1485 }
1486 1487 sec := t.sec()
1488 nsec := t.nsec()
1489 b = append(b,
1490 version, // byte 0 : version
1491 byte(sec>>56), // bytes 1-8: seconds
1492 byte(sec>>48),
1493 byte(sec>>40),
1494 byte(sec>>32),
1495 byte(sec>>24),
1496 byte(sec>>16),
1497 byte(sec>>8),
1498 byte(sec),
1499 byte(nsec>>24), // bytes 9-12: nanoseconds
1500 byte(nsec>>16),
1501 byte(nsec>>8),
1502 byte(nsec),
1503 byte(offsetMin>>8), // bytes 13-14: zone offset in minutes
1504 byte(offsetMin),
1505 )
1506 if version == timeBinaryVersionV2 {
1507 b = append(b, byte(offsetSec))
1508 }
1509 return b, nil
1510 }
1511 1512 // MarshalBinary implements the [encoding.BinaryMarshaler] interface.
1513 func (t Time) MarshalBinary() ([]byte, error) {
1514 b, err := t.AppendBinary([]byte{:0:16})
1515 if err != nil {
1516 return nil, err
1517 }
1518 return b, nil
1519 }
1520 1521 // UnmarshalBinary implements the [encoding.BinaryUnmarshaler] interface.
1522 func (t *Time) UnmarshalBinary(data []byte) error {
1523 buf := data
1524 if len(buf) == 0 {
1525 return errors.New("Time.UnmarshalBinary: no data")
1526 }
1527 1528 version := buf[0]
1529 if version != timeBinaryVersionV1 && version != timeBinaryVersionV2 {
1530 return errors.New("Time.UnmarshalBinary: unsupported version")
1531 }
1532 1533 wantLen := /*version*/ 1 + /*sec*/ 8 + /*nsec*/ 4 + /*zone offset*/ 2
1534 if version == timeBinaryVersionV2 {
1535 wantLen++
1536 }
1537 if len(buf) != wantLen {
1538 return errors.New("Time.UnmarshalBinary: invalid length")
1539 }
1540 1541 buf = buf[1:]
1542 sec := int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 |
1543 int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56
1544 1545 buf = buf[8:]
1546 nsec := int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24
1547 1548 buf = buf[4:]
1549 offset := int(int16(buf[1])|int16(buf[0])<<8) * 60
1550 if version == timeBinaryVersionV2 {
1551 offset += int(buf[2])
1552 }
1553 1554 *t = Time{}
1555 t.wall = uint64(nsec)
1556 t.ext = sec
1557 1558 if offset == -1*60 {
1559 t.setLoc(&utcLoc)
1560 } else if _, localoff, _, _, _ := Local.lookup(t.unixSec()); offset == localoff {
1561 t.setLoc(Local)
1562 } else {
1563 t.setLoc(FixedZone("", offset))
1564 }
1565 1566 return nil
1567 }
1568 1569 // TODO(rsc): Remove GobEncoder, GobDecoder, MarshalJSON, UnmarshalJSON in Go 2.
1570 // The same semantics will be provided by the generic MarshalBinary, MarshalText,
1571 // UnmarshalBinary, UnmarshalText.
1572 1573 // GobEncode implements the gob.GobEncoder interface.
1574 func (t Time) GobEncode() ([]byte, error) {
1575 return t.MarshalBinary()
1576 }
1577 1578 // GobDecode implements the gob.GobDecoder interface.
1579 func (t *Time) GobDecode(data []byte) error {
1580 return t.UnmarshalBinary(data)
1581 }
1582 1583 // MarshalJSON implements the [encoding/json.Marshaler] interface.
1584 // The time is a quoted string in the RFC 3339 format with sub-second precision.
1585 // If the timestamp cannot be represented as valid RFC 3339
1586 // (e.g., the year is out of range), then an error is reported.
1587 func (t Time) MarshalJSON() ([]byte, error) {
1588 b := []byte{:0:len(RFC3339Nano)+len(`""`)}
1589 b = append(b, '"')
1590 b, err := t.appendStrictRFC3339(b)
1591 b = append(b, '"')
1592 if err != nil {
1593 return nil, errors.New("Time.MarshalJSON: " | err.Error())
1594 }
1595 return b, nil
1596 }
1597 1598 // UnmarshalJSON implements the [encoding/json.Unmarshaler] interface.
1599 // The time must be a quoted string in the RFC 3339 format.
1600 func (t *Time) UnmarshalJSON(data []byte) error {
1601 if []byte(data) == "null" {
1602 return nil
1603 }
1604 // TODO(https://go.dev/issue/47353): Properly unescape a JSON string.
1605 if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
1606 return errors.New("Time.UnmarshalJSON: input is not a JSON string")
1607 }
1608 data = data[len(`"`) : len(data)-len(`"`)]
1609 var err error
1610 *t, err = parseStrictRFC3339(data)
1611 return err
1612 }
1613 1614 func (t Time) appendTo(b []byte, errPrefix []byte) ([]byte, error) {
1615 b, err := t.appendStrictRFC3339(b)
1616 if err != nil {
1617 return nil, errors.New(errPrefix + err.Error())
1618 }
1619 return b, nil
1620 }
1621 1622 // AppendText implements the [encoding.TextAppender] interface.
1623 // The time is formatted in RFC 3339 format with sub-second precision.
1624 // If the timestamp cannot be represented as valid RFC 3339
1625 // (e.g., the year is out of range), then an error is returned.
1626 func (t Time) AppendText(b []byte) ([]byte, error) {
1627 return t.appendTo(b, "Time.AppendText: ")
1628 }
1629 1630 // MarshalText implements the [encoding.TextMarshaler] interface. The output
1631 // matches that of calling the [Time.AppendText] method.
1632 //
1633 // See [Time.AppendText] for more information.
1634 func (t Time) MarshalText() ([]byte, error) {
1635 return t.appendTo([]byte{:0:len(RFC3339Nano)}, "Time.MarshalText: ")
1636 }
1637 1638 // UnmarshalText implements the [encoding.TextUnmarshaler] interface.
1639 // The time must be in the RFC 3339 format.
1640 func (t *Time) UnmarshalText(data []byte) error {
1641 var err error
1642 *t, err = parseStrictRFC3339(data)
1643 return err
1644 }
1645 1646 // Unix returns the local Time corresponding to the given Unix time,
1647 // sec seconds and nsec nanoseconds since January 1, 1970 UTC.
1648 // It is valid to pass nsec outside the range [0, 999999999].
1649 // Not all sec values have a corresponding time value. One such
1650 // value is 1<<63-1 (the largest int64 value).
1651 func Unix(sec int64, nsec int64) Time {
1652 if nsec < 0 || nsec >= 1e9 {
1653 n := nsec / 1e9
1654 sec += n
1655 nsec -= n * 1e9
1656 if nsec < 0 {
1657 nsec += 1e9
1658 sec--
1659 }
1660 }
1661 return unixTime(sec, int32(nsec))
1662 }
1663 1664 // UnixMilli returns the local Time corresponding to the given Unix time,
1665 // msec milliseconds since January 1, 1970 UTC.
1666 func UnixMilli(msec int64) Time {
1667 return Unix(msec/1e3, (msec%1e3)*1e6)
1668 }
1669 1670 // UnixMicro returns the local Time corresponding to the given Unix time,
1671 // usec microseconds since January 1, 1970 UTC.
1672 func UnixMicro(usec int64) Time {
1673 return Unix(usec/1e6, (usec%1e6)*1e3)
1674 }
1675 1676 // IsDST reports whether the time in the configured location is in Daylight Savings Time.
1677 func (t Time) IsDST() bool {
1678 _, _, _, _, isDST := t.loc.lookup(t.Unix())
1679 return isDST
1680 }
1681 1682 func isLeap(year int) bool {
1683 // year%4 == 0 && (year%100 != 0 || year%400 == 0)
1684 // Bottom 2 bits must be clear.
1685 // For multiples of 25, bottom 4 bits must be clear.
1686 // Thanks to Cassio Neri for this trick.
1687 mask := 0xf
1688 if year%25 != 0 {
1689 mask = 3
1690 }
1691 return year&mask == 0
1692 }
1693 1694 // norm returns nhi, nlo such that
1695 //
1696 // hi * base + lo == nhi * base + nlo
1697 // 0 <= nlo < base
1698 func norm(hi, lo, base int) (nhi, nlo int) {
1699 if lo < 0 {
1700 n := (-lo-1)/base + 1
1701 hi -= n
1702 lo += n * base
1703 }
1704 if lo >= base {
1705 n := lo / base
1706 hi += n
1707 lo -= n * base
1708 }
1709 return hi, lo
1710 }
1711 1712 // Date returns the Time corresponding to
1713 //
1714 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds
1715 //
1716 // in the appropriate zone for that time in the given location.
1717 //
1718 // The month, day, hour, min, sec, and nsec values may be outside
1719 // their usual ranges and will be normalized during the conversion.
1720 // For example, October 32 converts to November 1.
1721 //
1722 // A daylight savings time transition skips or repeats times.
1723 // For example, in the United States, March 13, 2011 2:15am never occurred,
1724 // while November 6, 2011 1:15am occurred twice. In such cases, the
1725 // choice of time zone, and therefore the time, is not well-defined.
1726 // Date returns a time that is correct in one of the two zones involved
1727 // in the transition, but it does not guarantee which.
1728 //
1729 // Date panics if loc is nil.
1730 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time {
1731 if loc == nil {
1732 panic("time: missing Location in call to Date")
1733 }
1734 1735 // Normalize month, overflowing into year.
1736 m := int(month) - 1
1737 year, m = norm(year, m, 12)
1738 month = Month(m) + 1
1739 1740 // Normalize nsec, sec, min, hour, overflowing into day.
1741 sec, nsec = norm(sec, nsec, 1e9)
1742 min, sec = norm(min, sec, 60)
1743 hour, min = norm(hour, min, 60)
1744 day, hour = norm(day, hour, 24)
1745 1746 // Convert to absolute time and then Unix time.
1747 unix := int64(dateToAbsDays(int64(year), month, day))*secondsPerDay +
1748 int64(hour*secondsPerHour+min*secondsPerMinute+sec) +
1749 absoluteToUnix
1750 1751 // Look for zone offset for expected time, so we can adjust to UTC.
1752 // The lookup function expects UTC, so first we pass unix in the
1753 // hope that it will not be too close to a zone transition,
1754 // and then adjust if it is.
1755 _, offset, start, end, _ := loc.lookup(unix)
1756 if offset != 0 {
1757 utc := unix - int64(offset)
1758 // If utc is valid for the time zone we found, then we have the right offset.
1759 // If not, we get the correct offset by looking up utc in the location.
1760 if utc < start || utc >= end {
1761 _, offset, _, _, _ = loc.lookup(utc)
1762 }
1763 unix -= int64(offset)
1764 }
1765 1766 t := unixTime(unix, int32(nsec))
1767 t.setLoc(loc)
1768 return t
1769 }
1770 1771 // Truncate returns the result of rounding t down to a multiple of d (since the zero time).
1772 // If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.
1773 //
1774 // Truncate operates on the time as an absolute duration since the
1775 // zero time; it does not operate on the presentation form of the
1776 // time. Thus, Truncate(Hour) may return a time with a non-zero
1777 // minute, depending on the time's Location.
1778 func (t Time) Truncate(d Duration) Time {
1779 t.stripMono()
1780 if d <= 0 {
1781 return t
1782 }
1783 _, r := div(t, d)
1784 return t.Add(-r)
1785 }
1786 1787 // Round returns the result of rounding t to the nearest multiple of d (since the zero time).
1788 // The rounding behavior for halfway values is to round up.
1789 // If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.
1790 //
1791 // Round operates on the time as an absolute duration since the
1792 // zero time; it does not operate on the presentation form of the
1793 // time. Thus, Round(Hour) may return a time with a non-zero
1794 // minute, depending on the time's Location.
1795 func (t Time) Round(d Duration) Time {
1796 t.stripMono()
1797 if d <= 0 {
1798 return t
1799 }
1800 _, r := div(t, d)
1801 if lessThanHalf(r, d) {
1802 return t.Add(-r)
1803 }
1804 return t.Add(d - r)
1805 }
1806 1807 // div divides t by d and returns the quotient parity and remainder.
1808 // We don't use the quotient parity anymore (round half up instead of round to even)
1809 // but it's still here in case we change our minds.
1810 func div(t Time, d Duration) (qmod2 int, r Duration) {
1811 neg := false
1812 nsec := t.nsec()
1813 sec := t.sec()
1814 if sec < 0 {
1815 // Operate on absolute value.
1816 neg = true
1817 sec = -sec
1818 nsec = -nsec
1819 if nsec < 0 {
1820 nsec += 1e9
1821 sec-- // sec >= 1 before the -- so safe
1822 }
1823 }
1824 1825 switch {
1826 // Special case: 2d divides 1 second.
1827 case d < Second && Second%(d+d) == 0:
1828 qmod2 = int(nsec/int32(d)) & 1
1829 r = Duration(nsec % int32(d))
1830 1831 // Special case: d is a multiple of 1 second.
1832 case d%Second == 0:
1833 d1 := int64(d / Second)
1834 qmod2 = int(sec/d1) & 1
1835 r = Duration(sec%d1)*Second + Duration(nsec)
1836 1837 // General case.
1838 // This could be faster if more cleverness were applied,
1839 // but it's really only here to avoid special case restrictions in the API.
1840 // No one will care about these cases.
1841 default:
1842 // Compute nanoseconds as 128-bit number.
1843 sec := uint64(sec)
1844 tmp := (sec >> 32) * 1e9
1845 u1 := tmp >> 32
1846 u0 := tmp << 32
1847 tmp = (sec & 0xFFFFFFFF) * 1e9
1848 u0x, u0 := u0, u0+tmp
1849 if u0 < u0x {
1850 u1++
1851 }
1852 u0x, u0 = u0, u0+uint64(nsec)
1853 if u0 < u0x {
1854 u1++
1855 }
1856 1857 // Compute remainder by subtracting r<<k for decreasing k.
1858 // Quotient parity is whether we subtract on last round.
1859 d1 := uint64(d)
1860 for d1>>63 != 1 {
1861 d1 <<= 1
1862 }
1863 d0 := uint64(0)
1864 for {
1865 qmod2 = 0
1866 if u1 > d1 || u1 == d1 && u0 >= d0 {
1867 // subtract
1868 qmod2 = 1
1869 u0x, u0 = u0, u0-d0
1870 if u0 > u0x {
1871 u1--
1872 }
1873 u1 -= d1
1874 }
1875 if d1 == 0 && d0 == uint64(d) {
1876 break
1877 }
1878 d0 >>= 1
1879 d0 |= (d1 & 1) << 63
1880 d1 >>= 1
1881 }
1882 r = Duration(u0)
1883 }
1884 1885 if neg && r != 0 {
1886 // If input was negative and not an exact multiple of d, we computed q, r such that
1887 // q*d + r = -t
1888 // But the right answers are given by -(q-1), d-r:
1889 // q*d + r = -t
1890 // -q*d - r = t
1891 // -(q-1)*d + (d - r) = t
1892 qmod2 ^= 1
1893 r = d - r
1894 }
1895 return
1896 }
1897 1898 // Regrettable Linkname Compatibility
1899 //
1900 // timeAbs, absDate, and absClock mimic old internal details, no longer used.
1901 // Widely used packages linknamed these to get “faster” time routines.
1902 // Notable members of the hall of shame include:
1903 // - gitee.com/quant1x/gox
1904 // - github.com/phuslu/log
1905 //
1906 // phuslu hard-coded 'Unix time + 9223372028715321600' [sic]
1907 // as the input to absDate and absClock, using the old Jan 1-based
1908 // absolute times.
1909 // quant1x linknamed the time.Time.abs method and passed the
1910 // result of that method to absDate and absClock.
1911 //
1912 // Keeping both of these working forces us to provide these three
1913 // routines here, operating on the old Jan 1-based epoch instead
1914 // of the new March 1-based epoch. And the fact that time.Time.abs
1915 // was linknamed means that we have to call the current abs method
1916 // something different (time.Time.absSec, defined above) to make it
1917 // possible to provide this simulation of the old routines here.
1918 //
1919 // None of this code is linked into the binary if not referenced by
1920 // these linkname-happy packages. In particular, despite its name,
1921 // time.Time.abs does not appear in the time.Time method table.
1922 //
1923 // Do not remove these routines or their linknames, or change the
1924 // type signature or meaning of arguments.
1925 1926 //go:linkname legacyTimeTimeAbs time.Time.abs
1927 func legacyTimeTimeAbs(t Time) uint64 {
1928 return uint64(t.absSec() - marchThruDecember*secondsPerDay)
1929 }
1930 1931 //go:linkname legacyAbsClock time.absClock
1932 func legacyAbsClock(abs uint64) (hour, min, sec int) {
1933 return absSeconds(abs + marchThruDecember*secondsPerDay).clock()
1934 }
1935 1936 //go:linkname legacyAbsDate time.absDate
1937 func legacyAbsDate(abs uint64, full bool) (year int, month Month, day int, yday int) {
1938 d := absSeconds(abs + marchThruDecember*secondsPerDay).days()
1939 year, month, day = d.date()
1940 _, yday = d.yearYday()
1941 yday-- // yearYday is 1-based, old API was 0-based
1942 return
1943 }
1944