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

View as plain text