OSDN Git Service

libgo: Update to weekly.2011-12-02.
[pf3gnuchains/gcc-fork.git] / libgo / go / 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 // A Time represents an instant in time with nanosecond precision.
11 //
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.
15 //
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.
19 //
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.
23 //
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.
30 //
31 type Time struct {
32         // sec gives the number of seconds elapsed since
33         // January 1, year 1 00:00:00 UTC.
34         sec int64
35
36         // nsec specifies a non-negative nanosecond
37         // offset within the second named by Seconds.
38         // It must be in the range [0, 999999999].
39         nsec int32
40
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.
46         loc *Location
47 }
48
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
52 }
53
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
57 }
58
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
63 // the locations.
64 func (t Time) Equal(u Time) bool {
65         return t.sec == u.sec && t.nsec == u.nsec
66 }
67
68 // A Month specifies a month of the year (January = 1, ...).
69 type Month int
70
71 const (
72         January Month = 1 + iota
73         February
74         March
75         April
76         May
77         June
78         July
79         August
80         September
81         October
82         November
83         December
84 )
85
86 var months = [...]string{
87         "January",
88         "February",
89         "March",
90         "April",
91         "May",
92         "June",
93         "July",
94         "August",
95         "September",
96         "October",
97         "November",
98         "December",
99 }
100
101 // String returns the English name of the month ("January", "February", ...).
102 func (m Month) String() string { return months[m-1] }
103
104 // A Weekday specifies a day of the week (Sunday = 0, ...).
105 type Weekday int
106
107 const (
108         Sunday Weekday = iota
109         Monday
110         Tuesday
111         Wednesday
112         Thursday
113         Friday
114         Saturday
115 )
116
117 var days = [...]string{
118         "Sunday",
119         "Monday",
120         "Tuesday",
121         "Wednesday",
122         "Thursday",
123         "Friday",
124         "Saturday",
125 }
126
127 // String returns the English name of the day ("Sunday", "Monday", ...).
128 func (d Weekday) String() string { return days[d] }
129
130 // Computations on time.
131 // 
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.
139 // 
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.
146 // 
147 // The Add and Sub computations are oblivious to the choice of epoch.
148 // 
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
162 //
163 //      sec = t % 60
164 //
165 // instead of
166 //
167 //      sec = t % 60
168 //      if sec < 0 {
169 //              sec += 60
170 //      }
171 //
172 // everywhere.
173 // 
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
182 // for 2401-2800.
183 // 
184 // Finally, it's convenient if the delta between the Unix epoch and
185 // long-ago epoch is representable by an int64 constant.
186 // 
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.
192 // 
193 // Times measured as an int64 seconds since the year 1—the representation
194 // used for Time's sec field—are called internal times.
195 // 
196 // Times measured as an int64 seconds since the year 1970 are called Unix
197 // times.
198 // 
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.
206 // 
207 // All this is opaque to clients of the API and can be changed if a
208 // better implementation presents itself.
209
210 const (
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
215
216         // The year of the zero Time.
217         // Assumed by the unixToInternal computation below.
218         internalYear = 1
219
220         // The year of the zero Unix time.
221         unixYear = 1970
222
223         // Offsets to convert between internal and absolute or Unix times.
224         absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay
225         internalToAbsolute       = -absoluteToInternal
226
227         unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
228         internalToUnix int64 = -unixToInternal
229 )
230
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
235 }
236
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 {
240         l := t.loc
241         if l == nil {
242                 l = &utcLoc
243         }
244         // Avoid function call if we hit the local time cache.
245         sec := t.sec + internalToUnix
246         if l != &utcLoc {
247                 if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
248                         sec += int64(l.cacheZone.offset)
249                 } else {
250                         _, offset, _, _, _ := l.lookup(sec)
251                         sec += int64(offset)
252                 }
253         }
254         return uint64(sec + (unixToInternal + internalToAbsolute))
255 }
256
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)
260         return
261 }
262
263 // Year returns the year in which t occurs.
264 func (t Time) Year() int {
265         year, _, _, _ := t.date(false)
266         return year
267 }
268
269 // Month returns the month of the year specified by t.
270 func (t Time) Month() Month {
271         _, month, _, _ := t.date(true)
272         return month
273 }
274
275 // Day returns the day of the month specified by t.
276 func (t Time) Day() int {
277         _, _, day, _ := t.date(true)
278         return day
279 }
280
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)
286 }
287
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 
291 // of year n+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.
295         const (
296                 Mon int = iota
297                 Tue
298                 Wed
299                 Thu
300                 Fri
301                 Sat
302                 Sun
303         )
304
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
311
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 {
318                 week++
319         }
320
321         // If the week number is still 0, we're in early January but in
322         // the last week of last year.
323         if week == 0 {
324                 year--
325                 week = 52
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)) {
330                         week++
331                 }
332         }
333
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 {
339                         year++
340                         week = 1
341                 }
342         }
343
344         return
345 }
346
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
354         return
355 }
356
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
360 }
361
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
365 }
366
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)
370 }
371
372 // Nanosecond returns the nanosecond offset within the second specified by t,
373 // in the range [0, 999999999].
374 func (t Time) Nanosecond() int {
375         return int(t.nsec)
376 }
377
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.
381 type Duration int64
382
383 // Common durations.  There is no definition for units of Day or larger
384 // to avoid confusion across daylight savings time zone transitions.
385 const (
386         Nanosecond  Duration = 1
387         Microsecond          = 1000 * Nanosecond
388         Millisecond          = 1000 * Microsecond
389         Second               = 1000 * Millisecond
390         Minute               = 60 * Second
391         Hour                 = 60 * Minute
392 )
393
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,
398 // with no unit.
399 func (d Duration) String() string {
400         // Largest time is 2540400h10m10.000000000s
401         var buf [32]byte
402         w := len(buf)
403
404         u := uint64(d)
405         neg := d < 0
406         if neg {
407                 u = -u
408         }
409
410         if u < uint64(Second) {
411                 // Special case: if duration is smaller than a second,
412                 // use smaller units, like 1.2ms
413                 var (
414                         prec int
415                         unit byte
416                 )
417                 switch {
418                 case u == 0:
419                         return "0"
420                 case u < uint64(Microsecond):
421                         // print nanoseconds
422                         prec = 0
423                         unit = 'n'
424                 case u < uint64(Millisecond):
425                         // print microseconds
426                         prec = 3
427                         unit = 'u'
428                 default:
429                         // print milliseconds
430                         prec = 6
431                         unit = 'm'
432                 }
433                 w -= 2
434                 buf[w] = unit
435                 buf[w+1] = 's'
436                 w, u = fmtFrac(buf[:w], u, prec)
437                 w = fmtInt(buf[:w], u)
438         } else {
439                 w--
440                 buf[w] = 's'
441
442                 w, u = fmtFrac(buf[:w], u, 9)
443
444                 // u is now integer seconds
445                 w = fmtInt(buf[:w], u%60)
446                 u /= 60
447
448                 // u is now integer minutes
449                 if u > 0 {
450                         w--
451                         buf[w] = 'm'
452                         w = fmtInt(buf[:w], u%60)
453                         u /= 60
454
455                         // u is now integer hours
456                         // Stop at hours because days can be different lengths.
457                         if u > 0 {
458                                 w--
459                                 buf[w] = 'h'
460                                 w = fmtInt(buf[:w], u)
461                         }
462                 }
463         }
464
465         if neg {
466                 w--
467                 buf[w] = '-'
468         }
469
470         return string(buf[w:])
471 }
472
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.
479         w := len(buf)
480         print := false
481         for i := 0; i < prec; i++ {
482                 digit := v % 10
483                 print = print || digit != 0
484                 if print {
485                         w--
486                         buf[w] = byte(digit) + '0'
487                 }
488                 v /= 10
489         }
490         if print {
491                 w--
492                 buf[w] = '.'
493         }
494         return w, v
495 }
496
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 {
500         w := len(buf)
501         if v == 0 {
502                 w--
503                 buf[w] = '0'
504         } else {
505                 for v > 0 {
506                         w--
507                         buf[w] = byte(v%10) + '0'
508                         v /= 10
509                 }
510         }
511         return w
512 }
513
514 // Nanoseconds returns the duration as an integer nanosecond count.
515 func (d Duration) Nanoseconds() int64 { return int64(d) }
516
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
524 // differently.
525
526 // Seconds returns the duration as a floating point number of seconds.
527 func (d Duration) Seconds() float64 {
528         sec := d / Second
529         nsec := d % Second
530         return float64(sec) + float64(nsec)*1e-9
531 }
532
533 // Minutes returns the duration as a floating point number of minutes.
534 func (d Duration) Minutes() float64 {
535         min := d / Minute
536         nsec := d % Minute
537         return float64(min) + float64(nsec)*(1e-9/60)
538 }
539
540 // Hours returns the duration as a floating point number of hours.
541 func (d Duration) Hours() float64 {
542         hour := d / Hour
543         nsec := d % Hour
544         return float64(hour) + float64(nsec)*(1e-9/60/60)
545 }
546
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)
551         if t.nsec > 1e9 {
552                 t.sec++
553                 t.nsec -= 1e9
554         } else if t.nsec < 0 {
555                 t.sec--
556                 t.nsec += 1e9
557         }
558         return t
559 }
560
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)
565 }
566
567 const (
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
576 )
577
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
583
584         // Account for 400 year cycles.
585         n := d / daysPer400Years
586         y := 400 * n
587         d -= daysPer400Years * n
588
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
594         n -= n >> 2
595         y += 100 * n
596         d -= daysPer100Years * n
597
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
602         y += 4 * n
603         d -= daysPer4Years * n
604
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.
609         n = d / 365
610         n -= n >> 2
611         y += n
612         d -= 365 * n
613
614         year = int(int64(y) + absoluteZeroYear)
615         yday = int(d)
616
617         if !full {
618                 return
619         }
620
621         day = yday
622         if isLeap(year) {
623                 // Leap year
624                 switch {
625                 case day > 31+29-1:
626                         // After leap day; pretend it wasn't there.
627                         day--
628                 case day == 31+29-1:
629                         // Leap day.
630                         month = February
631                         day = 29
632                         return
633                 }
634         }
635
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])
640         var begin int
641         if day >= end {
642                 month++
643                 begin = end
644         } else {
645                 begin = int(daysBefore[month])
646         }
647
648         month++ // because January is 1
649         day = day - begin + 1
650         return
651 }
652
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{
657         0,
658         31,
659         31 + 28,
660         31 + 28 + 31,
661         31 + 28 + 31 + 30,
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,
670 }
671
672 func daysIn(m Month, year int) int {
673         if m == February && isLeap(year) {
674                 return 29
675         }
676         return int(daysBefore[m+1] - daysBefore[m])
677 }
678
679 // Provided by package runtime.
680 func now() (sec int64, nsec int32)
681
682 // Now returns the current local time.
683 func Now() Time {
684         sec, nsec := now()
685         return Time{sec + unixToInternal, nsec, Local}
686 }
687
688 // UTC returns t with the location set to UTC.
689 func (t Time) UTC() Time {
690         t.loc = UTC
691         return t
692 }
693
694 // Local returns t with the location set to local time.
695 func (t Time) Local() Time {
696         t.loc = Local
697         return t
698 }
699
700 // In returns t with the location information set to loc.
701 //
702 // In panics if loc is nil.
703 func (t Time) In(loc *Location) Time {
704         if loc == nil {
705                 panic("time: missing Location in call to Time.In")
706         }
707         t.loc = loc
708         return t
709 }
710
711 // Location returns the time zone information associated with t.
712 func (t Time) Location() *Location {
713         l := t.loc
714         if l == nil {
715                 l = UTC
716         }
717         return l
718 }
719
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)
724         return
725 }
726
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
731 }
732
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)
737 }
738
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 {
744                 n := nsec / 1e9
745                 sec += n
746                 nsec -= n * 1e9
747                 if nsec < 0 {
748                         nsec += 1e9
749                         sec--
750                 }
751         }
752         return Time{sec + unixToInternal, int32(nsec), Local}
753 }
754
755 func isLeap(year int) bool {
756         return year%4 == 0 && (year%100 != 0 || year%400 == 0)
757 }
758
759 // norm returns nhi, nlo such that
760 //      hi * base + lo == nhi * base + nlo
761 //      0 <= nlo < base
762 func norm(hi, lo, base int) (nhi, nlo int) {
763         if lo < 0 {
764                 n := (-lo-1)/base + 1
765                 hi -= n
766                 lo += n * base
767         }
768         if lo >= base {
769                 n := lo / base
770                 hi += n
771                 lo -= n * base
772         }
773         return hi, lo
774 }
775
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.
779 //
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.
783 //
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.
790 //
791 // Date panics if loc is nil.
792 func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time {
793         if loc == nil {
794                 panic("time: missing Location in call to Date")
795         }
796
797         // Normalize month, overflowing into year.
798         m := int(month) - 1
799         year, m = norm(year, m, 12)
800         month = Month(m) + 1
801
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)
807
808         y := uint64(int64(year) - absoluteZeroYear)
809
810         // Compute days since the absolute epoch.
811
812         // Add in days from 400-year cycles.
813         n := y / 400
814         y -= 400 * n
815         d := daysPer400Years * n
816
817         // Add in 100-year cycles.
818         n = y / 100
819         y -= 100 * n
820         d += daysPer100Years * n
821
822         // Add in 4-year cycles.
823         n = y / 4
824         y -= 4 * n
825         d += daysPer4Years * n
826
827         // Add in non-leap years.
828         n = y
829         d += 365 * n
830
831         // Add in days before this month.
832         d += uint64(daysBefore[month-1])
833         if isLeap(year) && month >= March {
834                 d++ // February 29
835         }
836
837         // Add in days before today.
838         d += uint64(day - 1)
839
840         // Add in time elapsed today.
841         abs := d * secondsPerDay
842         abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec)
843
844         unix := int64(abs) + (absoluteToInternal + internalToUnix)
845
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)
851         if offset != 0 {
852                 switch utc := unix - int64(offset); {
853                 case utc < start:
854                         _, offset, _, _, _ = loc.lookup(start - 1)
855                 case utc >= end:
856                         _, offset, _, _, _ = loc.lookup(end)
857                 }
858                 unix -= int64(offset)
859         }
860
861         return Time{unix + unixToInternal, int32(nsec), loc}
862 }