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

View as plain text