Source file src/pkg/time/time.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package time provides functionality for measuring and displaying time.
6 //
7 // The calendrical calculations always assume a Gregorian calendar.
8 package time
9
10 import "errors"
11
12 // A Time represents an instant in time with nanosecond precision.
13 //
14 // Programs using times should typically store and pass them as values,
15 // not pointers. That is, time variables and struct fields should be of
16 // type time.Time, not *time.Time. A Time value can be used by
17 // multiple goroutines simultaneously.
18 //
19 // Time instants can be compared using the Before, After, and Equal methods.
20 // The Sub method subtracts two instants, producing a Duration.
21 // The Add method adds a Time and a Duration, producing a Time.
22 //
23 // The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.
24 // As this time is unlikely to come up in practice, the IsZero method gives
25 // a simple way of detecting a time that has not been initialized explicitly.
26 //
27 // Each Time has associated with it a Location, consulted when computing the
28 // presentation form of the time, such as in the Format, Hour, and Year methods.
29 // The methods Local, UTC, and In return a Time with a specific location.
30 // Changing the location in this way changes only the presentation; it does not
31 // change the instant in time being denoted and therefore does not affect the
32 // computations described in earlier paragraphs.
33 //
34 type Time struct {
35 // sec gives the number of seconds elapsed since
36 // January 1, year 1 00:00:00 UTC.
37 sec int64
38
39 // nsec specifies a non-negative nanosecond
40 // offset within the second named by Seconds.
41 // It must be in the range [0, 999999999].
42 nsec int32
43
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.
49 loc *Location
50 }
51
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
55 }
56
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
60 }
61
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
66 // the locations.
67 func (t Time) Equal(u Time) bool {
68 return t.sec == u.sec && t.nsec == u.nsec
69 }
70
71 // A Month specifies a month of the year (January = 1, ...).
72 type Month int
73
74 const (
75 January Month = 1 + iota
76 February
77 March
78 April
79 May
80 June
81 July
82 August
83 September
84 October
85 November
86 December
87 )
88
89 var months = [...]string{
90 "January",
91 "February",
92 "March",
93 "April",
94 "May",
95 "June",
96 "July",
97 "August",
98 "September",
99 "October",
100 "November",
101 "December",
102 }
103
104 // String returns the English name of the month ("January", "February", ...).
105 func (m Month) String() string { return months[m-1] }
106
107 // A Weekday specifies a day of the week (Sunday = 0, ...).
108 type Weekday int
109
110 const (
111 Sunday Weekday = iota
112 Monday
113 Tuesday
114 Wednesday
115 Thursday
116 Friday
117 Saturday
118 )
119
120 var days = [...]string{
121 "Sunday",
122 "Monday",
123 "Tuesday",
124 "Wednesday",
125 "Thursday",
126 "Friday",
127 "Saturday",
128 }
129
130 // String returns the English name of the day ("Sunday", "Monday", ...).
131 func (d Weekday) String() string { return days[d] }
132
133 // Computations on time.
134 //
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.
142 //
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.
149 //
150 // The Add and Sub computations are oblivious to the choice of epoch.
151 //
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
165 //
166 // sec = t % 60
167 //
168 // instead of
169 //
170 // sec = t % 60
171 // if sec < 0 {
172 // sec += 60
173 // }
174 //
175 // everywhere.
176 //
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
185 // for 2401-2800.
186 //
187 // Finally, it's convenient if the delta between the Unix epoch and
188 // long-ago epoch is representable by an int64 constant.
189 //
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.
195 //
196 // Times measured as an int64 seconds since the year 1—the representation
197 // used for Time's sec field—are called internal times.
198 //
199 // Times measured as an int64 seconds since the year 1970 are called Unix
200 // times.
201 //
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.
209 //
210 // All this is opaque to clients of the API and can be changed if a
211 // better implementation presents itself.
212
213 const (
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
218
219 // The year of the zero Time.
220 // Assumed by the unixToInternal computation below.
221 internalYear = 1
222
223 // The year of the zero Unix time.
224 unixYear = 1970
225
226 // Offsets to convert between internal and absolute or Unix times.
227 absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay
228 internalToAbsolute = -absoluteToInternal
229
230 unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
231 internalToUnix int64 = -unixToInternal
232 )
233
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
238 }
239
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 {
243 l := t.loc
244 if l == nil {
245 l = &utcLoc
246 }
247 // Avoid function call if we hit the local time cache.
248 sec := t.sec + internalToUnix
249 if l != &utcLoc {
250 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
251 sec += int64(l.cacheZone.offset)
252 } else {
253 _, offset, _, _, _ := l.lookup(sec)
254 sec += int64(offset)
255 }
256 }
257 return uint64(sec + (unixToInternal + internalToAbsolute))
258 }
259
260 // Date returns the year, month, and day in which t occurs.
261 func (t Time) Date() (year int, month Month, day int) {
262 year, month, day, _ = t.date(true)
263 return
264 }
265
266 // Year returns the year in which t occurs.
267 func (t Time) Year() int {
268 year, _, _, _ := t.date(false)
269 return year
270 }
271
272 // Month returns the month of the year specified by t.
273 func (t Time) Month() Month {
274 _, month, _, _ := t.date(true)
275 return month
276 }
277
278 // Day returns the day of the month specified by t.
279 func (t Time) Day() int {
280 _, _, day, _ := t.date(true)
281 return day
282 }
283
284 // Weekday returns the day of the week specified by t.
285 func (t Time) Weekday() Weekday {
286 // January 1 of the absolute year, like January 1 of 2001, was a Monday.
287 sec := (t.abs() + uint64(Monday)*secondsPerDay) % secondsPerWeek
288 return Weekday(int(sec) / secondsPerDay)
289 }
290
291 // ISOWeek returns the ISO 8601 year and week number in which t occurs.
292 // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to
293 // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1
294 // of year n+1.
295 func (t Time) ISOWeek() (year, week int) {
296 year, month, day, yday := t.date(true)
297 wday := int(t.Weekday()+6) % 7 // weekday but Monday = 0.
298 const (
299 Mon int = iota
300 Tue
301 Wed
302 Thu
303 Fri
304 Sat
305 Sun
306 )
307
308 // Calculate week as number of Mondays in year up to
309 // and including today, plus 1 because the first week is week 0.
310 // Putting the + 1 inside the numerator as a + 7 keeps the
311 // numerator from being negative, which would cause it to
312 // round incorrectly.
313 week = (yday - wday + 7) / 7
314
315 // The week number is now correct under the assumption
316 // that the first Monday of the year is in week 1.
317 // If Jan 1 is a Tuesday, Wednesday, or Thursday, the first Monday
318 // is actually in week 2.
319 jan1wday := (wday - yday + 7*53) % 7
320 if Tue <= jan1wday && jan1wday <= Thu {
321 week++
322 }
323
324 // If the week number is still 0, we're in early January but in
325 // the last week of last year.
326 if week == 0 {
327 year--
328 week = 52
329 // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday,
330 // meaning Jan 1 of the next year is a Friday
331 // or it was a leap year and Jan 1 of the next year is a Saturday.
332 if jan1wday == Fri || (jan1wday == Sat && isLeap(year)) {
333 week++
334 }
335 }
336
337 // December 29 to 31 are in week 1 of next year if
338 // they are after the last Thursday of the year and
339 // December 31 is a Monday, Tuesday, or Wednesday.
340 if month == December && day >= 29 && wday < Thu {
341 if dec31wday := (wday + 31 - day) % 7; Mon <= dec31wday && dec31wday <= Wed {
342 year++
343 week = 1
344 }
345 }
346
347 return
348 }
349
350 // Clock returns the hour, minute, and second within the day specified by t.
351 func (t Time) Clock() (hour, min, sec int) {
352 sec = int(t.abs() % secondsPerDay)
353 hour = sec / secondsPerHour
354 sec -= hour * secondsPerHour
355 min = sec / secondsPerMinute
356 sec -= min * secondsPerMinute
357 return
358 }
359
360 // Hour returns the hour within the day specified by t, in the range [0, 23].
361 func (t Time) Hour() int {
362 return int(t.abs()%secondsPerDay) / secondsPerHour
363 }
364
365 // Minute returns the minute offset within the hour specified by t, in the range [0, 59].
366 func (t Time) Minute() int {
367 return int(t.abs()%secondsPerHour) / secondsPerMinute
368 }
369
370 // Second returns the second offset within the minute specified by t, in the range [0, 59].
371 func (t Time) Second() int {
372 return int(t.abs() % secondsPerMinute)
373 }
374
375 // Nanosecond returns the nanosecond offset within the second specified by t,
376 // in the range [0, 999999999].
377 func (t Time) Nanosecond() int {
378 return int(t.nsec)
379 }
380
381 // A Duration represents the elapsed time between two instants
382 // as an int64 nanosecond count. The representation limits the
383 // largest representable duration to approximately 290 years.
384 type Duration int64
385
386 // Common durations. There is no definition for units of Day or larger
387 // to avoid confusion across daylight savings time zone transitions.
388 //
389 // To count the number of units in a Duration, divide:
390 // second := time.Second
391 // fmt.Print(int64(second/time.Millisecond)) // prints 1000
392 //
393 // To convert an integer number of units to a Duration, multiply:
394 // seconds := 10
395 // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
396 //
397 const (
398 Nanosecond Duration = 1
399 Microsecond = 1000 * Nanosecond
400 Millisecond = 1000 * Microsecond
401 Second = 1000 * Millisecond
402 Minute = 60 * Second
403 Hour = 60 * Minute
404 )
405
406 // String returns a string representing the duration in the form "72h3m0.5s".
407 // Leading zero units are omitted. As a special case, durations less than one
408 // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure
409 // that the leading digit is non-zero. The zero duration formats as 0,
410 // with no unit.
411 func (d Duration) String() string {
412 // Largest time is 2540400h10m10.000000000s
413 var buf [32]byte
414 w := len(buf)
415
416 u := uint64(d)
417 neg := d < 0
418 if neg {
419 u = -u
420 }
421
422 if u < uint64(Second) {
423 // Special case: if duration is smaller than a second,
424 // use smaller units, like 1.2ms
425 var (
426 prec int
427 unit byte
428 )
429 switch {
430 case u == 0:
431 return "0"
432 case u < uint64(Microsecond):
433 // print nanoseconds
434 prec = 0
435 unit = 'n'
436 case u < uint64(Millisecond):
437 // print microseconds
438 prec = 3
439 unit = 'u'
440 default:
441 // print milliseconds
442 prec = 6
443 unit = 'm'
444 }
445 w -= 2
446 buf[w] = unit
447 buf[w+1] = 's'
448 w, u = fmtFrac(buf[:w], u, prec)
449 w = fmtInt(buf[:w], u)
450 } else {
451 w--
452 buf[w] = 's'
453
454 w, u = fmtFrac(buf[:w], u, 9)
455
456 // u is now integer seconds
457 w = fmtInt(buf[:w], u%60)
458 u /= 60
459
460 // u is now integer minutes
461 if u > 0 {
462 w--
463 buf[w] = 'm'
464 w = fmtInt(buf[:w], u%60)
465 u /= 60
466
467 // u is now integer hours
468 // Stop at hours because days can be different lengths.
469 if u > 0 {
470 w--
471 buf[w] = 'h'
472 w = fmtInt(buf[:w], u)
473 }
474 }
475 }
476
477 if neg {
478 w--
479 buf[w] = '-'
480 }
481
482 return string(buf[w:])
483 }
484
485 // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
486 // tail of buf, omitting trailing zeros. it omits the decimal
487 // point too when the fraction is 0. It returns the index where the
488 // output bytes begin and the value v/10**prec.
489 func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
490 // Omit trailing zeros up to and including decimal point.
491 w := len(buf)
492 print := false
493 for i := 0; i < prec; i++ {
494 digit := v % 10
495 print = print || digit != 0
496 if print {
497 w--
498 buf[w] = byte(digit) + '0'
499 }
500 v /= 10
501 }
502 if print {
503 w--
504 buf[w] = '.'
505 }
506 return w, v
507 }
508
509 // fmtInt formats v into the tail of buf.
510 // It returns the index where the output begins.
511 func fmtInt(buf []byte, v uint64) int {
512 w := len(buf)
513 if v == 0 {
514 w--
515 buf[w] = '0'
516 } else {
517 for v > 0 {
518 w--
519 buf[w] = byte(v%10) + '0'
520 v /= 10
521 }
522 }
523 return w
524 }
525
526 // Nanoseconds returns the duration as an integer nanosecond count.
527 func (d Duration) Nanoseconds() int64 { return int64(d) }
528
529 // These methods return float64 because the dominant
530 // use case is for printing a floating point number like 1.5s, and
531 // a truncation to integer would make them not useful in those cases.
532 // Splitting the integer and fraction ourselves guarantees that
533 // converting the returned float64 to an integer rounds the same
534 // way that a pure integer conversion would have, even in cases
535 // where, say, float64(d.Nanoseconds())/1e9 would have rounded
536 // differently.
537
538 // Seconds returns the duration as a floating point number of seconds.
539 func (d Duration) Seconds() float64 {
540 sec := d / Second
541 nsec := d % Second
542 return float64(sec) + float64(nsec)*1e-9
543 }
544
545 // Minutes returns the duration as a floating point number of minutes.
546 func (d Duration) Minutes() float64 {
547 min := d / Minute
548 nsec := d % Minute
549 return float64(min) + float64(nsec)*(1e-9/60)
550 }
551
552 // Hours returns the duration as a floating point number of hours.
553 func (d Duration) Hours() float64 {
554 hour := d / Hour
555 nsec := d % Hour
556 return float64(hour) + float64(nsec)*(1e-9/60/60)
557 }
558
559 // Add returns the time t+d.
560 func (t Time) Add(d Duration) Time {
561 t.sec += int64(d / 1e9)
562 t.nsec += int32(d % 1e9)
563 if t.nsec >= 1e9 {
564 t.sec++
565 t.nsec -= 1e9
566 } else if t.nsec < 0 {
567 t.sec--
568 t.nsec += 1e9
569 }
570 return t
571 }
572
573 // Sub returns the duration t-u.
574 // To compute t-d for a duration d, use t.Add(-d).
575 func (t Time) Sub(u Time) Duration {
576 return Duration(t.sec-u.sec)*Second + Duration(t.nsec-u.nsec)
577 }
578
579 // Since returns the time elapsed since t.
580 // It is shorthand for time.Now().Sub(t).
581 func Since(t Time) Duration {
582 return Now().Sub(t)
583 }
584
585 // AddDate returns the time corresponding to adding the
586 // given number of years, months, and days to t.
587 // For example, AddDate(-1, 2, 3) applied to January 1, 2011
588 // returns March 4, 2010.
589 //
590 // AddDate normalizes its result in the same way that Date does,
591 // so, for example, adding one month to October 31 yields
592 // December 1, the normalized form for November 31.
593 func (t Time) AddDate(years int, months int, days int) Time {
594 year, month, day := t.Date()
595 hour, min, sec := t.Clock()
596 return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec), t.loc)
597 }
598
599 const (
600 secondsPerMinute = 60
601 secondsPerHour = 60 * 60
602 secondsPerDay = 24 * secondsPerHour
603 secondsPerWeek = 7 * secondsPerDay
604 daysPer400Years = 365*400 + 97
605 daysPer100Years = 365*100 + 24
606 daysPer4Years = 365*4 + 1
607 days1970To2001 = 31*365 + 8
608 )
609
610 // date computes the year and, only when full=true,
611 // the month and day in which t occurs.
612 func (t Time) date(full bool) (year int, month Month, day int, yday int) {
613 // Split into time and day.
614 d := t.abs() / secondsPerDay
615
616 // Account for 400 year cycles.
617 n := d / daysPer400Years
618 y := 400 * n
619 d -= daysPer400Years * n
620
621 // Cut off 100-year cycles.
622 // The last cycle has one extra leap year, so on the last day
623 // of that year, day / daysPer100Years will be 4 instead of 3.
624 // Cut it back down to 3 by subtracting n>>2.
625 n = d / daysPer100Years
626 n -= n >> 2
627 y += 100 * n
628 d -= daysPer100Years * n
629
630 // Cut off 4-year cycles.
631 // The last cycle has a missing leap year, which does not
632 // affect the computation.
633 n = d / daysPer4Years
634 y += 4 * n
635 d -= daysPer4Years * n
636
637 // Cut off years within a 4-year cycle.
638 // The last year is a leap year, so on the last day of that year,
639 // day / 365 will be 4 instead of 3. Cut it back down to 3
640 // by subtracting n>>2.
641 n = d / 365
642 n -= n >> 2
643 y += n
644 d -= 365 * n
645
646 year = int(int64(y) + absoluteZeroYear)
647 yday = int(d)
648
649 if !full {
650 return
651 }
652
653 day = yday
654 if isLeap(year) {
655 // Leap year
656 switch {
657 case day > 31+29-1:
658 // After leap day; pretend it wasn't there.
659 day--
660 case day == 31+29-1:
661 // Leap day.
662 month = February
663 day = 29
664 return
665 }
666 }
667
668 // Estimate month on assumption that every month has 31 days.
669 // The estimate may be too low by at most one month, so adjust.
670 month = Month(day / 31)
671 end := int(daysBefore[month+1])
672 var begin int
673 if day >= end {
674 month++
675 begin = end
676 } else {
677 begin = int(daysBefore[month])
678 }
679
680 month++ // because January is 1
681 day = day - begin + 1
682 return
683 }
684
685 // daysBefore[m] counts the number of days in a non-leap year
686 // before month m begins. There is an entry for m=12, counting
687 // the number of days before January of next year (365).
688 var daysBefore = [...]int32{
689 0,
690 31,
691 31 + 28,
692 31 + 28 + 31,
693 31 + 28 + 31 + 30,
694 31 + 28 + 31 + 30 + 31,
695 31 + 28 + 31 + 30 + 31 + 30,
696 31 + 28 + 31 + 30 + 31 + 30 + 31,
697 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
698 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
699 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
700 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
701 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31,
702 }
703
704 func daysIn(m Month, year int) int {
705 if m == February && isLeap(year) {
706 return 29
707 }
708 return int(daysBefore[m] - daysBefore[m-1])
709 }
710
711 // Provided by package runtime.
712 func now() (sec int64, nsec int32)
713
714 // Now returns the current local time.
715 func Now() Time {
716 sec, nsec := now()
717 return Time{sec + unixToInternal, nsec, Local}
718 }
719
720 // UTC returns t with the location set to UTC.
721 func (t Time) UTC() Time {
722 t.loc = UTC
723 return t
724 }
725
726 // Local returns t with the location set to local time.
727 func (t Time) Local() Time {
728 t.loc = Local
729 return t
730 }
731
732 // In returns t with the location information set to loc.
733 //
734 // In panics if loc is nil.
735 func (t Time) In(loc *Location) Time {
736 if loc == nil {
737 panic("time: missing Location in call to Time.In")
738 }
739 t.loc = loc
740 return t
741 }
742
743 // Location returns the time zone information associated with t.
744 func (t Time) Location() *Location {
745 l := t.loc
746 if l == nil {
747 l = UTC
748 }
749 return l
750 }
751
752 // Zone computes the time zone in effect at time t, returning the abbreviated
753 // name of the zone (such as "CET") and its offset in seconds east of UTC.
754 func (t Time) Zone() (name string, offset int) {
755 name, offset, _, _, _ = t.loc.lookup(t.sec + internalToUnix)
756 return
757 }
758
759 // Unix returns t as a Unix time, the number of seconds elapsed
760 // since January 1, 1970 UTC.
761 func (t Time) Unix() int64 {
762 return t.sec + internalToUnix
763 }
764
765 // UnixNano returns t as a Unix time, the number of nanoseconds elapsed
766 // since January 1, 1970 UTC. The result is undefined if the Unix time
767 // in nanoseconds cannot be represented by an int64. Note that this
768 // means the result of calling UnixNano on the zero Time is undefined.
769 func (t Time) UnixNano() int64 {
770 return (t.sec+internalToUnix)*1e9 + int64(t.nsec)
771 }
772
773 const timeGobVersion byte = 1
774
775 // GobEncode implements the gob.GobEncoder interface.
776 func (t Time) GobEncode() ([]byte, error) {
777 var offsetMin int16 // minutes east of UTC. -1 is UTC.
778
779 if t.Location() == &utcLoc {
780 offsetMin = -1
781 } else {
782 _, offset := t.Zone()
783 if offset%60 != 0 {
784 return nil, errors.New("Time.GobEncode: zone offset has fractional minute")
785 }
786 offset /= 60
787 if offset < -32768 || offset == -1 || offset > 32767 {
788 return nil, errors.New("Time.GobEncode: unexpected zone offset")
789 }
790 offsetMin = int16(offset)
791 }
792
793 enc := []byte{
794 timeGobVersion, // byte 0 : version
795 byte(t.sec >> 56), // bytes 1-8: seconds
796 byte(t.sec >> 48),
797 byte(t.sec >> 40),
798 byte(t.sec >> 32),
799 byte(t.sec >> 24),
800 byte(t.sec >> 16),
801 byte(t.sec >> 8),
802 byte(t.sec),
803 byte(t.nsec >> 24), // bytes 9-12: nanoseconds
804 byte(t.nsec >> 16),
805 byte(t.nsec >> 8),
806 byte(t.nsec),
807 byte(offsetMin >> 8), // bytes 13-14: zone offset in minutes
808 byte(offsetMin),
809 }
810
811 return enc, nil
812 }
813
814 // GobDecode implements the gob.GobDecoder interface.
815 func (t *Time) GobDecode(buf []byte) error {
816 if len(buf) == 0 {
817 return errors.New("Time.GobDecode: no data")
818 }
819
820 if buf[0] != timeGobVersion {
821 return errors.New("Time.GobDecode: unsupported version")
822 }
823
824 if len(buf) != /*version*/ 1+ /*sec*/ 8+ /*nsec*/ 4+ /*zone offset*/ 2 {
825 return errors.New("Time.GobDecode: invalid length")
826 }
827
828 buf = buf[1:]
829 t.sec = int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 |
830 int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56
831
832 buf = buf[8:]
833 t.nsec = int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24
834
835 buf = buf[4:]
836 offset := int(int16(buf[1])|int16(buf[0])<<8) * 60
837
838 if offset == -1*60 {
839 t.loc = &utcLoc
840 } else if _, localoff, _, _, _ := Local.lookup(t.sec + internalToUnix); offset == localoff {
841 t.loc = Local
842 } else {
843 t.loc = FixedZone("", offset)
844 }
845
846 return nil
847 }
848
849 // MarshalJSON implements the json.Marshaler interface.
850 // Time is formatted as RFC3339.
851 func (t Time) MarshalJSON() ([]byte, error) {
852 if y := t.Year(); y < 0 || y >= 10000 {
853 return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
854 }
855 return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil
856 }
857
858 // UnmarshalJSON implements the json.Unmarshaler interface.
859 // Time is expected in RFC3339 format.
860 func (t *Time) UnmarshalJSON(data []byte) (err error) {
861 // Fractional seconds are handled implicitly by Parse.
862 *t, err = Parse(`"`+RFC3339+`"`, string(data))
863 return
864 }
865
866 // Unix returns the local Time corresponding to the given Unix time,
867 // sec seconds and nsec nanoseconds since January 1, 1970 UTC.
868 // It is valid to pass nsec outside the range [0, 999999999].
869 func Unix(sec int64, nsec int64) Time {
870 if nsec < 0 || nsec >= 1e9 {
871 n := nsec / 1e9
872 sec += n
873 nsec -= n * 1e9
874 if nsec < 0 {
875 nsec += 1e9
876 sec--
877 }
878 }
879 return Time{sec + unixToInternal, int32(nsec), Local}
880 }
881
882 func isLeap(year int) bool {
883 return year%4 == 0 && (year%100 != 0 || year%400 == 0)
884 }
885
886 // norm returns nhi, nlo such that
887 // hi * base + lo == nhi * base + nlo
888 // 0 <= nlo < base
889 func norm(hi, lo, base int) (nhi, nlo int) {
890 if lo < 0 {
891 n := (-lo-1)/base + 1
892 hi -= n
893 lo += n * base
894 }
895 if lo >= base {
896 n := lo / base
897 hi += n
898 lo -= n * base
899 }
900 return hi, lo
901 }
902
903 // Date returns the Time corresponding to
904 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds
905 // in the appropriate zone for that time in the given location.
906 //
907 // The month, day, hour, min, sec, and nsec values may be outside
908 // their usual ranges and will be normalized during the conversion.
909 // For example, October 32 converts to November 1.
910 //
911 // A daylight savings time transition skips or repeats times.
912 // For example, in the United States, March 13, 2011 2:15am never occurred,
913 // while November 6, 2011 1:15am occurred twice. In such cases, the
914 // choice of time zone, and therefore the time, is not well-defined.
915 // Date returns a time that is correct in one of the two zones involved
916 // in the transition, but it does not guarantee which.
917 //
918 // Date panics if loc is nil.
919 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time {
920 if loc == nil {
921 panic("time: missing Location in call to Date")
922 }
923
924 // Normalize month, overflowing into year.
925 m := int(month) - 1
926 year, m = norm(year, m, 12)
927 month = Month(m) + 1
928
929 // Normalize nsec, sec, min, hour, overflowing into day.
930 sec, nsec = norm(sec, nsec, 1e9)
931 min, sec = norm(min, sec, 60)
932 hour, min = norm(hour, min, 60)
933 day, hour = norm(day, hour, 24)
934
935 y := uint64(int64(year) - absoluteZeroYear)
936
937 // Compute days since the absolute epoch.
938
939 // Add in days from 400-year cycles.
940 n := y / 400
941 y -= 400 * n
942 d := daysPer400Years * n
943
944 // Add in 100-year cycles.
945 n = y / 100
946 y -= 100 * n
947 d += daysPer100Years * n
948
949 // Add in 4-year cycles.
950 n = y / 4
951 y -= 4 * n
952 d += daysPer4Years * n
953
954 // Add in non-leap years.
955 n = y
956 d += 365 * n
957
958 // Add in days before this month.
959 d += uint64(daysBefore[month-1])
960 if isLeap(year) && month >= March {
961 d++ // February 29
962 }
963
964 // Add in days before today.
965 d += uint64(day - 1)
966
967 // Add in time elapsed today.
968 abs := d * secondsPerDay
969 abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec)
970
971 unix := int64(abs) + (absoluteToInternal + internalToUnix)
972
973 // Look for zone offset for t, so we can adjust to UTC.
974 // The lookup function expects UTC, so we pass t in the
975 // hope that it will not be too close to a zone transition,
976 // and then adjust if it is.
977 _, offset, _, start, end := loc.lookup(unix)
978 if offset != 0 {
979 switch utc := unix - int64(offset); {
980 case utc < start:
981 _, offset, _, _, _ = loc.lookup(start - 1)
982 case utc >= end:
983 _, offset, _, _, _ = loc.lookup(end)
984 }
985 unix -= int64(offset)
986 }
987
988 return Time{unix + unixToInternal, int32(nsec), loc}
989 }