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