...
Run Format

Source file src/pkg/time/time.go

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

View as plain text