Black Lives Matter. Support the Equal Justice Initiative.

Source file src/time/time.go

Documentation: time

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

View as plain text