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.
10 // A Time represents an instant in time with nanosecond precision.
12 // Programs using times should typically store and pass them as values,
13 // not pointers. That is, time variables and struct fields should be of
14 // type time.Time, not *time.Time.
16 // Time instants can be compared using the Before, After, and Equal methods.
17 // The Sub method subtracts two instants, producing a Duration.
18 // The Add method adds a Time and a Duration, producing a Time.
20 // The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.
21 // As this time is unlikely to come up in practice, the IsZero method gives
22 // a simple way of detecting a time that has not been initialized explicitly.
24 // Each Time has associated with it a Location, consulted when computing the
25 // presentation form of the time, such as in the Format, Hour, and Year methods.
26 // The methods Local, UTC, and In return a Time with a specific location.
27 // Changing the location in this way changes only the presentation; it does not
28 // change the instant in time being denoted and therefore does not affect the
29 // computations described in earlier paragraphs.
32 // sec gives the number of seconds elapsed since
33 // January 1, year 1 00:00:00 UTC.
36 // nsec specifies a non-negative nanosecond
37 // offset within the second named by Seconds.
38 // It must be in the range [0, 999999999].
41 // loc specifies the Location that should be used to
42 // determine the minute, hour, month, day, and year
43 // that correspond to this Time.
44 // Only the zero Time has a nil Location.
45 // In that case it is interpreted to mean UTC.
49 // After reports whether the time instant t is after u.
50 func (t Time) After(u Time) bool {
51 return t.sec > u.sec || t.sec == u.sec && t.nsec > u.nsec
54 // Before reports whether the time instant t is before u.
55 func (t Time) Before(u Time) bool {
56 return t.sec < u.sec || t.sec == u.sec && t.nsec < u.nsec
59 // Equal reports whether t and u represent the same time instant.
60 // Two times can be equal even if they are in different locations.
61 // For example, 6:00 +0200 CEST and 4:00 UTC are Equal.
62 // This comparison is different from using t == u, which also compares
64 func (t Time) Equal(u Time) bool {
65 return t.sec == u.sec && t.nsec == u.nsec
68 // A Month specifies a month of the year (January = 1, ...).
72 January Month = 1 + iota
86 var months = [...]string{
101 // String returns the English name of the month ("January", "February", ...).
102 func (m Month) String() string { return months[m-1] }
104 // A Weekday specifies a day of the week (Sunday = 0, ...).
108 Sunday Weekday = iota
117 var days = [...]string{
127 // String returns the English name of the day ("Sunday", "Monday", ...).
128 func (d Weekday) String() string { return days[d] }
130 // Computations on time.
132 // The zero value for a Time is defined to be
133 // January 1, year 1, 00:00:00.000000000 UTC
134 // which (1) looks like a zero, or as close as you can get in a date
135 // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to
136 // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a
137 // non-negative year even in time zones west of UTC, unlike 1-1-0
138 // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York.
140 // The zero Time value does not force a specific epoch for the time
141 // representation. For example, to use the Unix epoch internally, we
142 // could define that to distinguish a zero value from Jan 1 1970, that
143 // time would be represented by sec=-1, nsec=1e9. However, it does
144 // suggest a representation, namely using 1-1-1 00:00:00 UTC as the
145 // epoch, and that's what we do.
147 // The Add and Sub computations are oblivious to the choice of epoch.
149 // The presentation computations - year, month, minute, and so on - all
150 // rely heavily on division and modulus by positive constants. For
151 // calendrical calculations we want these divisions to round down, even
152 // for negative values, so that the remainder is always positive, but
153 // Go's division (like most hardware divison instructions) rounds to
154 // zero. We can still do those computations and then adjust the result
155 // for a negative numerator, but it's annoying to write the adjustment
156 // over and over. Instead, we can change to a different epoch so long
157 // ago that all the times we care about will be positive, and then round
158 // to zero and round down coincide. These presentation routines already
159 // have to add the zone offset, so adding the translation to the
160 // alternate epoch is cheap. For example, having a non-negative time t
161 // means that we can write
174 // The calendar runs on an exact 400 year cycle: a 400-year calendar
175 // printed for 1970-2469 will apply as well to 2470-2869. Even the days
176 // of the week match up. It simplifies the computations to choose the
177 // cycle boundaries so that the exceptional years are always delayed as
178 // long as possible. That means choosing a year equal to 1 mod 400, so
179 // that the first leap year is the 4th year, the first missed leap year
180 // is the 100th year, and the missed missed leap year is the 400th year.
181 // So we'd prefer instead to print a calendar for 2001-2400 and reuse it
184 // Finally, it's convenient if the delta between the Unix epoch and
185 // long-ago epoch is representable by an int64 constant.
187 // These three considerations—choose an epoch as early as possible, that
188 // uses a year equal to 1 mod 400, and that is no more than 2⁶³ seconds
189 // earlier than 1970—bring us to the year -292277022399. We refer to
190 // this year as the absolute zero year, and to times measured as a uint64
191 // seconds since this year as absolute times.
193 // Times measured as an int64 seconds since the year 1—the representation
194 // used for Time's sec field—are called internal times.
196 // Times measured as an int64 seconds since the year 1970 are called Unix
199 // It is tempting to just use the year 1 as the absolute epoch, defining
200 // that the routines are only valid for years >= 1. However, the
201 // routines would then be invalid when displaying the epoch in time zones
202 // west of UTC, since it is year 0. It doesn't seem tenable to say that
203 // printing the zero time correctly isn't supported in half the time
204 // zones. By comparison, it's reasonable to mishandle some times in
205 // the year -292277022399.
207 // All this is opaque to clients of the API and can be changed if a
208 // better implementation presents itself.
211 // The unsigned zero year for internal calculations.
212 // Must be 1 mod 400, and times before it will not compute correctly,
213 // but otherwise can be changed at will.
214 absoluteZeroYear = -292277022399
216 // The year of the zero Time.
217 // Assumed by the unixToInternal computation below.
220 // The year of the zero Unix time.
223 // Offsets to convert between internal and absolute or Unix times.
224 absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay
225 internalToAbsolute = -absoluteToInternal
227 unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
228 internalToUnix int64 = -unixToInternal
231 // IsZero reports whether t represents the zero time instant,
232 // January 1, year 1, 00:00:00 UTC.
233 func (t Time) IsZero() bool {
234 return t.sec == 0 && t.nsec == 0
237 // abs returns the time t as an absolute time, adjusted by the zone offset.
238 // It is called when computing a presentation property like Month or Hour.
239 func (t Time) abs() uint64 {
244 // Avoid function call if we hit the local time cache.
245 sec := t.sec + internalToUnix
247 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
248 sec += int64(l.cacheZone.offset)
250 _, offset, _, _, _ := l.lookup(sec)
254 return uint64(sec + (unixToInternal + internalToAbsolute))
257 // Date returns the year, month, and day in which t occurs.
258 func (t Time) Date() (year int, month Month, day int) {
259 year, month, day, _ = t.date(true)
263 // Year returns the year in which t occurs.
264 func (t Time) Year() int {
265 year, _, _, _ := t.date(false)
269 // Month returns the month of the year specified by t.
270 func (t Time) Month() Month {
271 _, month, _, _ := t.date(true)
275 // Day returns the day of the month specified by t.
276 func (t Time) Day() int {
277 _, _, day, _ := t.date(true)
281 // Weekday returns the day of the week specified by t.
282 func (t Time) Weekday() Weekday {
283 // January 1 of the absolute year, like January 1 of 2001, was a Monday.
284 sec := (t.abs() + uint64(Monday)*secondsPerDay) % secondsPerWeek
285 return Weekday(int(sec) / secondsPerDay)
288 // ISOWeek returns the ISO 8601 year and week number in which t occurs.
289 // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to
290 // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1
292 func (t Time) ISOWeek() (year, week int) {
293 year, month, day, yday := t.date(true)
294 wday := int(t.Weekday()+6) % 7 // weekday but Monday = 0.
305 // Calculate week as number of Mondays in year up to
306 // and including today, plus 1 because the first week is week 0.
307 // Putting the + 1 inside the numerator as a + 7 keeps the
308 // numerator from being negative, which would cause it to
309 // round incorrectly.
310 week = (yday - wday + 7) / 7
312 // The week number is now correct under the assumption
313 // that the first Monday of the year is in week 1.
314 // If Jan 1 is a Tuesday, Wednesday, or Thursday, the first Monday
315 // is actually in week 2.
316 jan1wday := (wday - yday + 7*53) % 7
317 if Tue <= jan1wday && jan1wday <= Thu {
321 // If the week number is still 0, we're in early January but in
322 // the last week of last year.
326 // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday,
327 // meaning Jan 1 of the next year is a Friday
328 // or it was a leap year and Jan 1 of the next year is a Saturday.
329 if jan1wday == Fri || (jan1wday == Sat && isLeap(year)) {
334 // December 29 to 31 are in week 1 of next year if
335 // they are after the last Thursday of the year and
336 // December 31 is a Monday, Tuesday, or Wednesday.
337 if month == December && day >= 29 && wday < Thu {
338 if dec31wday := (wday + 31 - day) % 7; Mon <= dec31wday && dec31wday <= Wed {
347 // Clock returns the hour, minute, and second within the day specified by t.
348 func (t Time) Clock() (hour, min, sec int) {
349 sec = int(t.abs() % secondsPerDay)
350 hour = sec / secondsPerHour
351 sec -= hour * secondsPerHour
352 min = sec / secondsPerMinute
353 sec -= min * secondsPerMinute
357 // Hour returns the hour within the day specified by t, in the range [0, 23].
358 func (t Time) Hour() int {
359 return int(t.abs()%secondsPerDay) / secondsPerHour
362 // Minute returns the minute offset within the hour specified by t, in the range [0, 59].
363 func (t Time) Minute() int {
364 return int(t.abs()%secondsPerHour) / secondsPerMinute
367 // Second returns the second offset within the minute specified by t, in the range [0, 59].
368 func (t Time) Second() int {
369 return int(t.abs() % secondsPerMinute)
372 // Nanosecond returns the nanosecond offset within the second specified by t,
373 // in the range [0, 999999999].
374 func (t Time) Nanosecond() int {
378 // A Duration represents the elapsed time between two instants
379 // as an int64 nanosecond count. The representation limits the
380 // largest representable duration to approximately 290 years.
383 // Common durations. There is no definition for units of Day or larger
384 // to avoid confusion across daylight savings time zone transitions.
386 Nanosecond Duration = 1
387 Microsecond = 1000 * Nanosecond
388 Millisecond = 1000 * Microsecond
389 Second = 1000 * Millisecond
394 // Duration returns a string representing the duration in the form "72h3m0.5s".
395 // Leading zero units are omitted. As a special case, durations less than one
396 // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure
397 // that the leading digit is non-zero. The zero duration formats as 0,
399 func (d Duration) String() string {
400 // Largest time is 2540400h10m10.000000000s
410 if u < uint64(Second) {
411 // Special case: if duration is smaller than a second,
412 // use smaller units, like 1.2ms
420 case u < uint64(Microsecond):
424 case u < uint64(Millisecond):
425 // print microseconds
429 // print milliseconds
436 w, u = fmtFrac(buf[:w], u, prec)
437 w = fmtInt(buf[:w], u)
442 w, u = fmtFrac(buf[:w], u, 9)
444 // u is now integer seconds
445 w = fmtInt(buf[:w], u%60)
448 // u is now integer minutes
452 w = fmtInt(buf[:w], u%60)
455 // u is now integer hours
456 // Stop at hours because days can be different lengths.
460 w = fmtInt(buf[:w], u)
470 return string(buf[w:])
473 // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
474 // tail of buf, omitting trailing zeros. it omits the decimal
475 // point too when the fraction is 0. It returns the index where the
476 // output bytes begin and the value v/10**prec.
477 func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
478 // Omit trailing zeros up to and including decimal point.
481 for i := 0; i < prec; i++ {
483 print = print || digit != 0
486 buf[w] = byte(digit) + '0'
497 // fmtInt formats v into the tail of buf.
498 // It returns the index where the output begins.
499 func fmtInt(buf []byte, v uint64) int {
507 buf[w] = byte(v%10) + '0'
514 // Nanoseconds returns the duration as an integer nanosecond count.
515 func (d Duration) Nanoseconds() int64 { return int64(d) }
517 // These methods return float64 because the dominant
518 // use case is for printing a floating point number like 1.5s, and
519 // a truncation to integer would make them not useful in those cases.
520 // Splitting the integer and fraction ourselves guarantees that
521 // converting the returned float64 to an integer rounds the same
522 // way that a pure integer conversion would have, even in cases
523 // where, say, float64(d.Nanoseconds())/1e9 would have rounded
526 // Seconds returns the duration as a floating point number of seconds.
527 func (d Duration) Seconds() float64 {
530 return float64(sec) + float64(nsec)*1e-9
533 // Minutes returns the duration as a floating point number of minutes.
534 func (d Duration) Minutes() float64 {
537 return float64(min) + float64(nsec)*(1e-9/60)
540 // Hours returns the duration as a floating point number of hours.
541 func (d Duration) Hours() float64 {
544 return float64(hour) + float64(nsec)*(1e-9/60/60)
547 // Add returns the time t+d.
548 func (t Time) Add(d Duration) Time {
549 t.sec += int64(d / 1e9)
550 t.nsec += int32(d % 1e9)
554 } else if t.nsec < 0 {
561 // Sub returns the duration t-u.
562 // To compute t-d for a duration d, use t.Add(-d).
563 func (t Time) Sub(u Time) Duration {
564 return Duration(t.sec-u.sec)*Second + Duration(t.nsec-u.nsec)
568 secondsPerMinute = 60
569 secondsPerHour = 60 * 60
570 secondsPerDay = 24 * secondsPerHour
571 secondsPerWeek = 7 * secondsPerDay
572 daysPer400Years = 365*400 + 97
573 daysPer100Years = 365*100 + 24
574 daysPer4Years = 365*4 + 1
575 days1970To2001 = 31*365 + 8
578 // date computes the year and, only when full=true,
579 // the month and day in which t occurs.
580 func (t Time) date(full bool) (year int, month Month, day int, yday int) {
581 // Split into time and day.
582 d := t.abs() / secondsPerDay
584 // Account for 400 year cycles.
585 n := d / daysPer400Years
587 d -= daysPer400Years * n
589 // Cut off 100-year cycles.
590 // The last cycle has one extra leap year, so on the last day
591 // of that year, day / daysPer100Years will be 4 instead of 3.
592 // Cut it back down to 3 by subtracting n>>2.
593 n = d / daysPer100Years
596 d -= daysPer100Years * n
598 // Cut off 4-year cycles.
599 // The last cycle has a missing leap year, which does not
600 // affect the computation.
601 n = d / daysPer4Years
603 d -= daysPer4Years * n
605 // Cut off years within a 4-year cycle.
606 // The last year is a leap year, so on the last day of that year,
607 // day / 365 will be 4 instead of 3. Cut it back down to 3
608 // by subtracting n>>2.
614 year = int(int64(y) + absoluteZeroYear)
626 // After leap day; pretend it wasn't there.
636 // Estimate month on assumption that every month has 31 days.
637 // The estimate may be too low by at most one month, so adjust.
638 month = Month(day / 31)
639 end := int(daysBefore[month+1])
645 begin = int(daysBefore[month])
648 month++ // because January is 1
649 day = day - begin + 1
653 // daysBefore[m] counts the number of days in a non-leap year
654 // before month m begins. There is an entry for m=12, counting
655 // the number of days before January of next year (365).
656 var daysBefore = [...]int32{
662 31 + 28 + 31 + 30 + 31,
663 31 + 28 + 31 + 30 + 31 + 30,
664 31 + 28 + 31 + 30 + 31 + 30 + 31,
665 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
666 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
667 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
668 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
669 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31,
672 func daysIn(m Month, year int) int {
673 if m == February && isLeap(year) {
676 return int(daysBefore[m+1] - daysBefore[m])
679 // Provided by package runtime.
680 func now() (sec int64, nsec int32)
682 // Now returns the current local time.
685 return Time{sec + unixToInternal, nsec, Local}
688 // UTC returns t with the location set to UTC.
689 func (t Time) UTC() Time {
694 // Local returns t with the location set to local time.
695 func (t Time) Local() Time {
700 // In returns t with the location information set to loc.
702 // In panics if loc is nil.
703 func (t Time) In(loc *Location) Time {
705 panic("time: missing Location in call to Time.In")
711 // Location returns the time zone information associated with t.
712 func (t Time) Location() *Location {
720 // Zone computes the time zone in effect at time t, returning the abbreviated
721 // name of the zone (such as "CET") and its offset in seconds east of UTC.
722 func (t Time) Zone() (name string, offset int) {
723 name, offset, _, _, _ = t.loc.lookup(t.sec + internalToUnix)
727 // Unix returns the Unix time, the number of seconds elapsed
728 // since January 1, 1970 UTC.
729 func (t Time) Unix() int64 {
730 return t.sec + internalToUnix
733 // UnixNano returns the Unix time, the number of nanoseconds elapsed
734 // since January 1, 1970 UTC.
735 func (t Time) UnixNano() int64 {
736 return (t.sec+internalToUnix)*1e9 + int64(t.nsec)
739 // Unix returns the local Time corresponding to the given Unix time,
740 // sec seconds and nsec nanoseconds since January 1, 1970 UTC.
741 // It is valid to pass nsec outside the range [0, 999999999].
742 func Unix(sec int64, nsec int64) Time {
743 if nsec < 0 || nsec >= 1e9 {
752 return Time{sec + unixToInternal, int32(nsec), Local}
755 func isLeap(year int) bool {
756 return year%4 == 0 && (year%100 != 0 || year%400 == 0)
759 // norm returns nhi, nlo such that
760 // hi * base + lo == nhi * base + nlo
762 func norm(hi, lo, base int) (nhi, nlo int) {
764 n := (-lo-1)/base + 1
776 // Date returns the Time corresponding to
777 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds
778 // in the appropriate zone for that time in the given location.
780 // The month, day, hour, min, sec, and nsec values may be outside
781 // their usual ranges and will be normalized during the conversion.
782 // For example, October 32 converts to November 1.
784 // A daylight savings time transition skips or repeats times.
785 // For example, in the United States, March 13, 2011 2:15am never occurred,
786 // while November 6, 2011 1:15am occurred twice. In such cases, the
787 // choice of time zone, and therefore the time, is not well-defined.
788 // Date returns a time that is correct in one of the two zones involved
789 // in the transition, but it does not guarantee which.
791 // Date panics if loc is nil.
792 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time {
794 panic("time: missing Location in call to Date")
797 // Normalize month, overflowing into year.
799 year, m = norm(year, m, 12)
802 // Normalize nsec, sec, min, hour, overflowing into day.
803 sec, nsec = norm(sec, nsec, 1e9)
804 min, sec = norm(min, sec, 60)
805 hour, min = norm(hour, min, 60)
806 day, hour = norm(day, hour, 24)
808 y := uint64(int64(year) - absoluteZeroYear)
810 // Compute days since the absolute epoch.
812 // Add in days from 400-year cycles.
815 d := daysPer400Years * n
817 // Add in 100-year cycles.
820 d += daysPer100Years * n
822 // Add in 4-year cycles.
825 d += daysPer4Years * n
827 // Add in non-leap years.
831 // Add in days before this month.
832 d += uint64(daysBefore[month-1])
833 if isLeap(year) && month >= March {
837 // Add in days before today.
840 // Add in time elapsed today.
841 abs := d * secondsPerDay
842 abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec)
844 unix := int64(abs) + (absoluteToInternal + internalToUnix)
846 // Look for zone offset for t, so we can adjust to UTC.
847 // The lookup function expects UTC, so we pass t in the
848 // hope that it will not be too close to a zone transition,
849 // and then adjust if it is.
850 _, offset, _, start, end := loc.lookup(unix)
852 switch utc := unix - int64(offset); {
854 _, offset, _, _, _ = loc.lookup(start - 1)
856 _, offset, _, _, _ = loc.lookup(end)
858 unix -= int64(offset)
861 return Time{unix + unixToInternal, int32(nsec), loc}