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