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

View as plain text