github.com/embeddedgo/x@v0.0.6-0.20191217015414-d79a36f562e7/time/time.go (about)

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