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

View as plain text