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.
5 // Package time provides functionality for measuring and displaying time.
7 // The calendrical calculations always assume a Gregorian calendar.
12 // A Time represents an instant in time with nanosecond precision.
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.
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.
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.
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.
35 // sec gives the number of seconds elapsed since
36 // January 1, year 1 00:00:00 UTC.
39 // nsec specifies a non-negative nanosecond
40 // offset within the second named by Seconds.
41 // It must be in the range [0, 999999999].
44 // loc specifies the Location that should be used to
45 // determine the minute, hour, month, day, and year
46 // that correspond to this Time.
47 // Only the zero Time has a nil Location.
48 // In that case it is interpreted to mean UTC.
52 // After reports whether the time instant t is after u.
53 func (t Time) After(u Time) bool {
54 return t.sec > u.sec || t.sec == u.sec && t.nsec > u.nsec
57 // Before reports whether the time instant t is before u.
58 func (t Time) Before(u Time) bool {
59 return t.sec < u.sec || t.sec == u.sec && t.nsec < u.nsec
62 // Equal reports whether t and u represent the same time instant.
63 // Two times can be equal even if they are in different locations.
64 // For example, 6:00 +0200 CEST and 4:00 UTC are Equal.
65 // This comparison is different from using t == u, which also compares
67 func (t Time) Equal(u Time) bool {
68 return t.sec == u.sec && t.nsec == u.nsec
71 // A Month specifies a month of the year (January = 1, ...).
75 January Month = 1 + iota
89 var months = [...]string{
104 // String returns the English name of the month ("January", "February", ...).
105 func (m Month) String() string { return months[m-1] }
107 // A Weekday specifies a day of the week (Sunday = 0, ...).
111 Sunday Weekday = iota
120 var days = [...]string{
130 // String returns the English name of the day ("Sunday", "Monday", ...).
131 func (d Weekday) String() string { return days[d] }
133 // Computations on time.
135 // The zero value for a Time is defined to be
136 // January 1, year 1, 00:00:00.000000000 UTC
137 // which (1) looks like a zero, or as close as you can get in a date
138 // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to
139 // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a
140 // non-negative year even in time zones west of UTC, unlike 1-1-0
141 // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York.
143 // The zero Time value does not force a specific epoch for the time
144 // representation. For example, to use the Unix epoch internally, we
145 // could define that to distinguish a zero value from Jan 1 1970, that
146 // time would be represented by sec=-1, nsec=1e9. However, it does
147 // suggest a representation, namely using 1-1-1 00:00:00 UTC as the
148 // epoch, and that's what we do.
150 // The Add and Sub computations are oblivious to the choice of epoch.
152 // The presentation computations - year, month, minute, and so on - all
153 // rely heavily on division and modulus by positive constants. For
154 // calendrical calculations we want these divisions to round down, even
155 // for negative values, so that the remainder is always positive, but
156 // Go's division (like most hardware division instructions) rounds to
157 // zero. We can still do those computations and then adjust the result
158 // for a negative numerator, but it's annoying to write the adjustment
159 // over and over. Instead, we can change to a different epoch so long
160 // ago that all the times we care about will be positive, and then round
161 // to zero and round down coincide. These presentation routines already
162 // have to add the zone offset, so adding the translation to the
163 // alternate epoch is cheap. For example, having a non-negative time t
164 // means that we can write
177 // The calendar runs on an exact 400 year cycle: a 400-year calendar
178 // printed for 1970-2469 will apply as well to 2470-2869. Even the days
179 // of the week match up. It simplifies the computations to choose the
180 // cycle boundaries so that the exceptional years are always delayed as
181 // long as possible. That means choosing a year equal to 1 mod 400, so
182 // that the first leap year is the 4th year, the first missed leap year
183 // is the 100th year, and the missed missed leap year is the 400th year.
184 // So we'd prefer instead to print a calendar for 2001-2400 and reuse it
187 // Finally, it's convenient if the delta between the Unix epoch and
188 // long-ago epoch is representable by an int64 constant.
190 // These three considerations—choose an epoch as early as possible, that
191 // uses a year equal to 1 mod 400, and that is no more than 2⁶³ seconds
192 // earlier than 1970—bring us to the year -292277022399. We refer to
193 // this year as the absolute zero year, and to times measured as a uint64
194 // seconds since this year as absolute times.
196 // Times measured as an int64 seconds since the year 1—the representation
197 // used for Time's sec field—are called internal times.
199 // Times measured as an int64 seconds since the year 1970 are called Unix
202 // It is tempting to just use the year 1 as the absolute epoch, defining
203 // that the routines are only valid for years >= 1. However, the
204 // routines would then be invalid when displaying the epoch in time zones
205 // west of UTC, since it is year 0. It doesn't seem tenable to say that
206 // printing the zero time correctly isn't supported in half the time
207 // zones. By comparison, it's reasonable to mishandle some times in
208 // the year -292277022399.
210 // All this is opaque to clients of the API and can be changed if a
211 // better implementation presents itself.
214 // The unsigned zero year for internal calculations.
215 // Must be 1 mod 400, and times before it will not compute correctly,
216 // but otherwise can be changed at will.
217 absoluteZeroYear = -292277022399
219 // The year of the zero Time.
220 // Assumed by the unixToInternal computation below.
223 // The year of the zero Unix time.
226 // Offsets to convert between internal and absolute or Unix times.
227 absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay
228 internalToAbsolute = -absoluteToInternal
230 unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
231 internalToUnix int64 = -unixToInternal
234 // IsZero reports whether t represents the zero time instant,
235 // January 1, year 1, 00:00:00 UTC.
236 func (t Time) IsZero() bool {
237 return t.sec == 0 && t.nsec == 0
240 // abs returns the time t as an absolute time, adjusted by the zone offset.
241 // It is called when computing a presentation property like Month or Hour.
242 func (t Time) abs() uint64 {
244 // Avoid function calls when possible.
245 if l == nil || l == &localLoc {
248 sec := t.sec + internalToUnix
250 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
251 sec += int64(l.cacheZone.offset)
253 _, offset, _, _, _ := l.lookup(sec)
257 return uint64(sec + (unixToInternal + internalToAbsolute))
260 // locabs is a combination of the Zone and abs methods,
261 // extracting both return values from a single zone lookup.
262 func (t Time) locabs() (name string, offset int, abs uint64) {
264 if l == nil || l == &localLoc {
267 // Avoid function call if we hit the local time cache.
268 sec := t.sec + internalToUnix
270 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
271 name = l.cacheZone.name
272 offset = l.cacheZone.offset
274 name, offset, _, _, _ = l.lookup(sec)
280 abs = uint64(sec + (unixToInternal + internalToAbsolute))
284 // Date returns the year, month, and day in which t occurs.
285 func (t Time) Date() (year int, month Month, day int) {
286 year, month, day, _ = t.date(true)
290 // Year returns the year in which t occurs.
291 func (t Time) Year() int {
292 year, _, _, _ := t.date(false)
296 // Month returns the month of the year specified by t.
297 func (t Time) Month() Month {
298 _, month, _, _ := t.date(true)
302 // Day returns the day of the month specified by t.
303 func (t Time) Day() int {
304 _, _, day, _ := t.date(true)
308 // Weekday returns the day of the week specified by t.
309 func (t Time) Weekday() Weekday {
310 return absWeekday(t.abs())
313 // absWeekday is like Weekday but operates on an absolute time.
314 func absWeekday(abs uint64) Weekday {
315 // January 1 of the absolute year, like January 1 of 2001, was a Monday.
316 sec := (abs + uint64(Monday)*secondsPerDay) % secondsPerWeek
317 return Weekday(int(sec) / secondsPerDay)
320 // ISOWeek returns the ISO 8601 year and week number in which t occurs.
321 // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to
322 // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1
324 func (t Time) ISOWeek() (year, week int) {
325 year, month, day, yday := t.date(true)
326 wday := int(t.Weekday()+6) % 7 // weekday but Monday = 0.
337 // Calculate week as number of Mondays in year up to
338 // and including today, plus 1 because the first week is week 0.
339 // Putting the + 1 inside the numerator as a + 7 keeps the
340 // numerator from being negative, which would cause it to
341 // round incorrectly.
342 week = (yday - wday + 7) / 7
344 // The week number is now correct under the assumption
345 // that the first Monday of the year is in week 1.
346 // If Jan 1 is a Tuesday, Wednesday, or Thursday, the first Monday
347 // is actually in week 2.
348 jan1wday := (wday - yday + 7*53) % 7
349 if Tue <= jan1wday && jan1wday <= Thu {
353 // If the week number is still 0, we're in early January but in
354 // the last week of last year.
358 // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday,
359 // meaning Jan 1 of the next year is a Friday
360 // or it was a leap year and Jan 1 of the next year is a Saturday.
361 if jan1wday == Fri || (jan1wday == Sat && isLeap(year)) {
366 // December 29 to 31 are in week 1 of next year if
367 // they are after the last Thursday of the year and
368 // December 31 is a Monday, Tuesday, or Wednesday.
369 if month == December && day >= 29 && wday < Thu {
370 if dec31wday := (wday + 31 - day) % 7; Mon <= dec31wday && dec31wday <= Wed {
379 // Clock returns the hour, minute, and second within the day specified by t.
380 func (t Time) Clock() (hour, min, sec int) {
381 return absClock(t.abs())
384 // absClock is like clock but operates on an absolute time.
385 func absClock(abs uint64) (hour, min, sec int) {
386 sec = int(abs % secondsPerDay)
387 hour = sec / secondsPerHour
388 sec -= hour * secondsPerHour
389 min = sec / secondsPerMinute
390 sec -= min * secondsPerMinute
394 // Hour returns the hour within the day specified by t, in the range [0, 23].
395 func (t Time) Hour() int {
396 return int(t.abs()%secondsPerDay) / secondsPerHour
399 // Minute returns the minute offset within the hour specified by t, in the range [0, 59].
400 func (t Time) Minute() int {
401 return int(t.abs()%secondsPerHour) / secondsPerMinute
404 // Second returns the second offset within the minute specified by t, in the range [0, 59].
405 func (t Time) Second() int {
406 return int(t.abs() % secondsPerMinute)
409 // Nanosecond returns the nanosecond offset within the second specified by t,
410 // in the range [0, 999999999].
411 func (t Time) Nanosecond() int {
415 // YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years,
416 // and [1,366] in leap years.
417 func (t Time) YearDay() int {
418 _, _, _, yday := t.date(false)
422 // A Duration represents the elapsed time between two instants
423 // as an int64 nanosecond count. The representation limits the
424 // largest representable duration to approximately 290 years.
427 // Common durations. There is no definition for units of Day or larger
428 // to avoid confusion across daylight savings time zone transitions.
430 // To count the number of units in a Duration, divide:
431 // second := time.Second
432 // fmt.Print(int64(second/time.Millisecond)) // prints 1000
434 // To convert an integer number of units to a Duration, multiply:
436 // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
439 Nanosecond Duration = 1
440 Microsecond = 1000 * Nanosecond
441 Millisecond = 1000 * Microsecond
442 Second = 1000 * Millisecond
447 // String returns a string representing the duration in the form "72h3m0.5s".
448 // Leading zero units are omitted. As a special case, durations less than one
449 // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure
450 // that the leading digit is non-zero. The zero duration formats as 0,
452 func (d Duration) String() string {
453 // Largest time is 2540400h10m10.000000000s
463 if u < uint64(Second) {
464 // Special case: if duration is smaller than a second,
465 // use smaller units, like 1.2ms
473 case u < uint64(Microsecond):
477 case u < uint64(Millisecond):
478 // print microseconds
482 // print milliseconds
489 w, u = fmtFrac(buf[:w], u, prec)
490 w = fmtInt(buf[:w], u)
495 w, u = fmtFrac(buf[:w], u, 9)
497 // u is now integer seconds
498 w = fmtInt(buf[:w], u%60)
501 // u is now integer minutes
505 w = fmtInt(buf[:w], u%60)
508 // u is now integer hours
509 // Stop at hours because days can be different lengths.
513 w = fmtInt(buf[:w], u)
523 return string(buf[w:])
526 // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
527 // tail of buf, omitting trailing zeros. it omits the decimal
528 // point too when the fraction is 0. It returns the index where the
529 // output bytes begin and the value v/10**prec.
530 func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
531 // Omit trailing zeros up to and including decimal point.
534 for i := 0; i < prec; i++ {
536 print = print || digit != 0
539 buf[w] = byte(digit) + '0'
550 // fmtInt formats v into the tail of buf.
551 // It returns the index where the output begins.
552 func fmtInt(buf []byte, v uint64) int {
560 buf[w] = byte(v%10) + '0'
567 // Nanoseconds returns the duration as an integer nanosecond count.
568 func (d Duration) Nanoseconds() int64 { return int64(d) }
570 // These methods return float64 because the dominant
571 // use case is for printing a floating point number like 1.5s, and
572 // a truncation to integer would make them not useful in those cases.
573 // Splitting the integer and fraction ourselves guarantees that
574 // converting the returned float64 to an integer rounds the same
575 // way that a pure integer conversion would have, even in cases
576 // where, say, float64(d.Nanoseconds())/1e9 would have rounded
579 // Seconds returns the duration as a floating point number of seconds.
580 func (d Duration) Seconds() float64 {
583 return float64(sec) + float64(nsec)*1e-9
586 // Minutes returns the duration as a floating point number of minutes.
587 func (d Duration) Minutes() float64 {
590 return float64(min) + float64(nsec)*(1e-9/60)
593 // Hours returns the duration as a floating point number of hours.
594 func (d Duration) Hours() float64 {
597 return float64(hour) + float64(nsec)*(1e-9/60/60)
600 // Add returns the time t+d.
601 func (t Time) Add(d Duration) Time {
602 t.sec += int64(d / 1e9)
603 t.nsec += int32(d % 1e9)
607 } else if t.nsec < 0 {
614 // Sub returns the duration t-u.
615 // To compute t-d for a duration d, use t.Add(-d).
616 func (t Time) Sub(u Time) Duration {
617 return Duration(t.sec-u.sec)*Second + Duration(t.nsec-u.nsec)
620 // Since returns the time elapsed since t.
621 // It is shorthand for time.Now().Sub(t).
622 func Since(t Time) Duration {
626 // AddDate returns the time corresponding to adding the
627 // given number of years, months, and days to t.
628 // For example, AddDate(-1, 2, 3) applied to January 1, 2011
629 // returns March 4, 2010.
631 // AddDate normalizes its result in the same way that Date does,
632 // so, for example, adding one month to October 31 yields
633 // December 1, the normalized form for November 31.
634 func (t Time) AddDate(years int, months int, days int) Time {
635 year, month, day := t.Date()
636 hour, min, sec := t.Clock()
637 return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec), t.loc)
641 secondsPerMinute = 60
642 secondsPerHour = 60 * 60
643 secondsPerDay = 24 * secondsPerHour
644 secondsPerWeek = 7 * secondsPerDay
645 daysPer400Years = 365*400 + 97
646 daysPer100Years = 365*100 + 24
647 daysPer4Years = 365*4 + 1
648 days1970To2001 = 31*365 + 8
651 // date computes the year, day of year, and when full=true,
652 // the month and day in which t occurs.
653 func (t Time) date(full bool) (year int, month Month, day int, yday int) {
654 return absDate(t.abs(), full)
657 // absDate is like date but operates on an absolute time.
658 func absDate(abs uint64, full bool) (year int, month Month, day int, yday int) {
659 // Split into time and day.
660 d := abs / secondsPerDay
662 // Account for 400 year cycles.
663 n := d / daysPer400Years
665 d -= daysPer400Years * n
667 // Cut off 100-year cycles.
668 // The last cycle has one extra leap year, so on the last day
669 // of that year, day / daysPer100Years will be 4 instead of 3.
670 // Cut it back down to 3 by subtracting n>>2.
671 n = d / daysPer100Years
674 d -= daysPer100Years * n
676 // Cut off 4-year cycles.
677 // The last cycle has a missing leap year, which does not
678 // affect the computation.
679 n = d / daysPer4Years
681 d -= daysPer4Years * n
683 // Cut off years within a 4-year cycle.
684 // The last year is a leap year, so on the last day of that year,
685 // day / 365 will be 4 instead of 3. Cut it back down to 3
686 // by subtracting n>>2.
692 year = int(int64(y) + absoluteZeroYear)
704 // After leap day; pretend it wasn't there.
714 // Estimate month on assumption that every month has 31 days.
715 // The estimate may be too low by at most one month, so adjust.
716 month = Month(day / 31)
717 end := int(daysBefore[month+1])
723 begin = int(daysBefore[month])
726 month++ // because January is 1
727 day = day - begin + 1
731 // daysBefore[m] counts the number of days in a non-leap year
732 // before month m begins. There is an entry for m=12, counting
733 // the number of days before January of next year (365).
734 var daysBefore = [...]int32{
740 31 + 28 + 31 + 30 + 31,
741 31 + 28 + 31 + 30 + 31 + 30,
742 31 + 28 + 31 + 30 + 31 + 30 + 31,
743 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
744 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
745 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
746 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
747 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31,
750 func daysIn(m Month, year int) int {
751 if m == February && isLeap(year) {
754 return int(daysBefore[m] - daysBefore[m-1])
757 // Provided by package runtime.
758 func now() (sec int64, nsec int32)
760 // Now returns the current local time.
763 return Time{sec + unixToInternal, nsec, Local}
766 // UTC returns t with the location set to UTC.
767 func (t Time) UTC() Time {
772 // Local returns t with the location set to local time.
773 func (t Time) Local() Time {
778 // In returns t with the location information set to loc.
780 // In panics if loc is nil.
781 func (t Time) In(loc *Location) Time {
783 panic("time: missing Location in call to Time.In")
789 // Location returns the time zone information associated with t.
790 func (t Time) Location() *Location {
798 // Zone computes the time zone in effect at time t, returning the abbreviated
799 // name of the zone (such as "CET") and its offset in seconds east of UTC.
800 func (t Time) Zone() (name string, offset int) {
801 name, offset, _, _, _ = t.loc.lookup(t.sec + internalToUnix)
805 // Unix returns t as a Unix time, the number of seconds elapsed
806 // since January 1, 1970 UTC.
807 func (t Time) Unix() int64 {
808 return t.sec + internalToUnix
811 // UnixNano returns t as a Unix time, the number of nanoseconds elapsed
812 // since January 1, 1970 UTC. The result is undefined if the Unix time
813 // in nanoseconds cannot be represented by an int64. Note that this
814 // means the result of calling UnixNano on the zero Time is undefined.
815 func (t Time) UnixNano() int64 {
816 return (t.sec+internalToUnix)*1e9 + int64(t.nsec)
819 const timeGobVersion byte = 1
821 // GobEncode implements the gob.GobEncoder interface.
822 func (t Time) GobEncode() ([]byte, error) {
823 var offsetMin int16 // minutes east of UTC. -1 is UTC.
825 if t.Location() == &utcLoc {
828 _, offset := t.Zone()
830 return nil, errors.New("Time.GobEncode: zone offset has fractional minute")
833 if offset < -32768 || offset == -1 || offset > 32767 {
834 return nil, errors.New("Time.GobEncode: unexpected zone offset")
836 offsetMin = int16(offset)
840 timeGobVersion, // byte 0 : version
841 byte(t.sec >> 56), // bytes 1-8: seconds
849 byte(t.nsec >> 24), // bytes 9-12: nanoseconds
853 byte(offsetMin >> 8), // bytes 13-14: zone offset in minutes
860 // GobDecode implements the gob.GobDecoder interface.
861 func (t *Time) GobDecode(buf []byte) error {
863 return errors.New("Time.GobDecode: no data")
866 if buf[0] != timeGobVersion {
867 return errors.New("Time.GobDecode: unsupported version")
870 if len(buf) != /*version*/ 1+ /*sec*/ 8+ /*nsec*/ 4+ /*zone offset*/ 2 {
871 return errors.New("Time.GobDecode: invalid length")
875 t.sec = int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 |
876 int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56
879 t.nsec = int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24
882 offset := int(int16(buf[1])|int16(buf[0])<<8) * 60
886 } else if _, localoff, _, _, _ := Local.lookup(t.sec + internalToUnix); offset == localoff {
889 t.loc = FixedZone("", offset)
895 // MarshalJSON implements the json.Marshaler interface.
896 // Time is formatted as RFC3339.
897 func (t Time) MarshalJSON() ([]byte, error) {
898 if y := t.Year(); y < 0 || y >= 10000 {
899 return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
901 return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil
904 // UnmarshalJSON implements the json.Unmarshaler interface.
905 // Time is expected in RFC3339 format.
906 func (t *Time) UnmarshalJSON(data []byte) (err error) {
907 // Fractional seconds are handled implicitly by Parse.
908 *t, err = Parse(`"`+RFC3339+`"`, string(data))
912 // Unix returns the local Time corresponding to the given Unix time,
913 // sec seconds and nsec nanoseconds since January 1, 1970 UTC.
914 // It is valid to pass nsec outside the range [0, 999999999].
915 func Unix(sec int64, nsec int64) Time {
916 if nsec < 0 || nsec >= 1e9 {
925 return Time{sec + unixToInternal, int32(nsec), Local}
928 func isLeap(year int) bool {
929 return year%4 == 0 && (year%100 != 0 || year%400 == 0)
932 // norm returns nhi, nlo such that
933 // hi * base + lo == nhi * base + nlo
935 func norm(hi, lo, base int) (nhi, nlo int) {
937 n := (-lo-1)/base + 1
949 // Date returns the Time corresponding to
950 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds
951 // in the appropriate zone for that time in the given location.
953 // The month, day, hour, min, sec, and nsec values may be outside
954 // their usual ranges and will be normalized during the conversion.
955 // For example, October 32 converts to November 1.
957 // A daylight savings time transition skips or repeats times.
958 // For example, in the United States, March 13, 2011 2:15am never occurred,
959 // while November 6, 2011 1:15am occurred twice. In such cases, the
960 // choice of time zone, and therefore the time, is not well-defined.
961 // Date returns a time that is correct in one of the two zones involved
962 // in the transition, but it does not guarantee which.
964 // Date panics if loc is nil.
965 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time {
967 panic("time: missing Location in call to Date")
970 // Normalize month, overflowing into year.
972 year, m = norm(year, m, 12)
975 // Normalize nsec, sec, min, hour, overflowing into day.
976 sec, nsec = norm(sec, nsec, 1e9)
977 min, sec = norm(min, sec, 60)
978 hour, min = norm(hour, min, 60)
979 day, hour = norm(day, hour, 24)
981 y := uint64(int64(year) - absoluteZeroYear)
983 // Compute days since the absolute epoch.
985 // Add in days from 400-year cycles.
988 d := daysPer400Years * n
990 // Add in 100-year cycles.
993 d += daysPer100Years * n
995 // Add in 4-year cycles.
998 d += daysPer4Years * n
1000 // Add in non-leap years.
1004 // Add in days before this month.
1005 d += uint64(daysBefore[month-1])
1006 if isLeap(year) && month >= March {
1010 // Add in days before today.
1011 d += uint64(day - 1)
1013 // Add in time elapsed today.
1014 abs := d * secondsPerDay
1015 abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec)
1017 unix := int64(abs) + (absoluteToInternal + internalToUnix)
1019 // Look for zone offset for t, so we can adjust to UTC.
1020 // The lookup function expects UTC, so we pass t in the
1021 // hope that it will not be too close to a zone transition,
1022 // and then adjust if it is.
1023 _, offset, _, start, end := loc.lookup(unix)
1025 switch utc := unix - int64(offset); {
1027 _, offset, _, _, _ = loc.lookup(start - 1)
1029 _, offset, _, _, _ = loc.lookup(end)
1031 unix -= int64(offset)
1034 return Time{unix + unixToInternal, int32(nsec), loc}
1037 // Truncate returns the result of rounding t down to a multiple of d (since the zero time).
1038 // If d <= 0, Truncate returns t unchanged.
1039 func (t Time) Truncate(d Duration) Time {
1047 // Round returns the result of rounding t to the nearest multiple of d (since the zero time).
1048 // The rounding behavior for halfway values is to round up.
1049 // If d <= 0, Round returns t unchanged.
1050 func (t Time) Round(d Duration) Time {
1061 // div divides t by d and returns the quotient parity and remainder.
1062 // We don't use the quotient parity anymore (round half up instead of round to even)
1063 // but it's still here in case we change our minds.
1064 func div(t Time, d Duration) (qmod2 int, r Duration) {
1067 // Operate on absolute value.
1073 t.sec-- // t.sec >= 1 before the -- so safe
1078 // Special case: 2d divides 1 second.
1079 case d < Second && Second%(d+d) == 0:
1080 qmod2 = int(t.nsec/int32(d)) & 1
1081 r = Duration(t.nsec % int32(d))
1083 // Special case: d is a multiple of 1 second.
1085 d1 := int64(d / Second)
1086 qmod2 = int(t.sec/d1) & 1
1087 r = Duration(t.sec%d1)*Second + Duration(t.nsec)
1090 // This could be faster if more cleverness were applied,
1091 // but it's really only here to avoid special case restrictions in the API.
1092 // No one will care about these cases.
1094 // Compute nanoseconds as 128-bit number.
1095 sec := uint64(t.sec)
1096 tmp := (sec >> 32) * 1e9
1099 tmp = uint64(sec&0xFFFFFFFF) * 1e9
1100 u0x, u0 := u0, u0+tmp
1104 u0x, u0 = u0, u0+uint64(t.nsec)
1109 // Compute remainder by subtracting r<<k for decreasing k.
1110 // Quotient parity is whether we subtract on last round.
1118 if u1 > d1 || u1 == d1 && u0 >= d0 {
1127 if d1 == 0 && d0 == uint64(d) {
1131 d0 |= (d1 & 1) << 63
1138 // If input was negative and not an exact multiple of d, we computed q, r such that
1140 // But the right answers are given by -(q-1), d-r:
1143 // -(q-1)*d + (d - r) = t