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

View as plain text