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