time.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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. // Package time provides functionality for measuring and displaying time.
  5. //
  6. // The calendrical calculations always assume a Gregorian calendar.
  7. package time
  8. import "errors"
  9. // A Time represents an instant in time with nanosecond precision.
  10. //
  11. // Programs using times should typically store and pass them as values,
  12. // not pointers. That is, time variables and struct fields should be of
  13. // type time.Time, not *time.Time. A Time value can be used by
  14. // multiple goroutines simultaneously.
  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. // Note that the Go == operator compares not just the time instant but also the
  32. // Location. Therefore, Time values should not be used as map or database keys
  33. // without first guaranteeing that the identical Location has been set for all
  34. // values, which can be achieved through use of the UTC or Local method.
  35. //
  36. type Time struct {
  37. // sec gives the number of seconds elapsed since
  38. // January 1, year 1 00:00:00 UTC.
  39. sec int64
  40. // nsec specifies a non-negative nanosecond
  41. // offset within the second named by Seconds.
  42. // It must be in the range [0, 999999999].
  43. nsec int32
  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. // After reports whether the time instant t is after u.
  52. func (t Time) After(u Time) bool {
  53. return t.sec > u.sec || t.sec == u.sec && t.nsec > u.nsec
  54. }
  55. // Before reports whether the time instant t is before u.
  56. func (t Time) Before(u Time) bool {
  57. return t.sec < u.sec || t.sec == u.sec && t.nsec < u.nsec
  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. // A Month specifies a month of the year (January = 1, ...).
  68. type Month int
  69. const (
  70. January Month = 1 + iota
  71. February
  72. March
  73. April
  74. May
  75. June
  76. July
  77. August
  78. September
  79. October
  80. November
  81. December
  82. )
  83. var months = [...]string{
  84. "January",
  85. "February",
  86. "March",
  87. "April",
  88. "May",
  89. "June",
  90. "July",
  91. "August",
  92. "September",
  93. "October",
  94. "November",
  95. "December",
  96. }
  97. // String returns the English name of the month ("January", "February", ...).
  98. func (m Month) String() string { return months[m-1] }
  99. // A Weekday specifies a day of the week (Sunday = 0, ...).
  100. type Weekday int
  101. const (
  102. Sunday Weekday = iota
  103. Monday
  104. Tuesday
  105. Wednesday
  106. Thursday
  107. Friday
  108. Saturday
  109. )
  110. var days = [...]string{
  111. "Sunday",
  112. "Monday",
  113. "Tuesday",
  114. "Wednesday",
  115. "Thursday",
  116. "Friday",
  117. "Saturday",
  118. }
  119. // String returns the English name of the day ("Sunday", "Monday", ...).
  120. func (d Weekday) String() string { return days[d] }
  121. // Computations on time.
  122. //
  123. // The zero value for a Time is defined to be
  124. // January 1, year 1, 00:00:00.000000000 UTC
  125. // which (1) looks like a zero, or as close as you can get in a date
  126. // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to
  127. // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a
  128. // non-negative year even in time zones west of UTC, unlike 1-1-0
  129. // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York.
  130. //
  131. // The zero Time value does not force a specific epoch for the time
  132. // representation. For example, to use the Unix epoch internally, we
  133. // could define that to distinguish a zero value from Jan 1 1970, that
  134. // time would be represented by sec=-1, nsec=1e9. However, it does
  135. // suggest a representation, namely using 1-1-1 00:00:00 UTC as the
  136. // epoch, and that's what we do.
  137. //
  138. // The Add and Sub computations are oblivious to the choice of epoch.
  139. //
  140. // The presentation computations - year, month, minute, and so on - all
  141. // rely heavily on division and modulus by positive constants. For
  142. // calendrical calculations we want these divisions to round down, even
  143. // for negative values, so that the remainder is always positive, but
  144. // Go's division (like most hardware division instructions) rounds to
  145. // zero. We can still do those computations and then adjust the result
  146. // for a negative numerator, but it's annoying to write the adjustment
  147. // over and over. Instead, we can change to a different epoch so long
  148. // ago that all the times we care about will be positive, and then round
  149. // to zero and round down coincide. These presentation routines already
  150. // have to add the zone offset, so adding the translation to the
  151. // alternate epoch is cheap. For example, having a non-negative time t
  152. // means that we can write
  153. //
  154. // sec = t % 60
  155. //
  156. // instead of
  157. //
  158. // sec = t % 60
  159. // if sec < 0 {
  160. // sec += 60
  161. // }
  162. //
  163. // everywhere.
  164. //
  165. // The calendar runs on an exact 400 year cycle: a 400-year calendar
  166. // printed for 1970-2469 will apply as well to 2470-2869. Even the days
  167. // of the week match up. It simplifies the computations to choose the
  168. // cycle boundaries so that the exceptional years are always delayed as
  169. // long as possible. That means choosing a year equal to 1 mod 400, so
  170. // that the first leap year is the 4th year, the first missed leap year
  171. // is the 100th year, and the missed missed leap year is the 400th year.
  172. // So we'd prefer instead to print a calendar for 2001-2400 and reuse it
  173. // for 2401-2800.
  174. //
  175. // Finally, it's convenient if the delta between the Unix epoch and
  176. // long-ago epoch is representable by an int64 constant.
  177. //
  178. // These three considerations—choose an epoch as early as possible, that
  179. // uses a year equal to 1 mod 400, and that is no more than 2⁶³ seconds
  180. // earlier than 1970—bring us to the year -292277022399. We refer to
  181. // this year as the absolute zero year, and to times measured as a uint64
  182. // seconds since this year as absolute times.
  183. //
  184. // Times measured as an int64 seconds since the year 1—the representation
  185. // used for Time's sec field—are called internal times.
  186. //
  187. // Times measured as an int64 seconds since the year 1970 are called Unix
  188. // times.
  189. //
  190. // It is tempting to just use the year 1 as the absolute epoch, defining
  191. // that the routines are only valid for years >= 1. However, the
  192. // routines would then be invalid when displaying the epoch in time zones
  193. // west of UTC, since it is year 0. It doesn't seem tenable to say that
  194. // printing the zero time correctly isn't supported in half the time
  195. // zones. By comparison, it's reasonable to mishandle some times in
  196. // the year -292277022399.
  197. //
  198. // All this is opaque to clients of the API and can be changed if a
  199. // better implementation presents itself.
  200. const (
  201. // The unsigned zero year for internal calculations.
  202. // Must be 1 mod 400, and times before it will not compute correctly,
  203. // but otherwise can be changed at will.
  204. absoluteZeroYear = -292277022399
  205. // The year of the zero Time.
  206. // Assumed by the unixToInternal computation below.
  207. internalYear = 1
  208. // The year of the zero Unix time.
  209. unixYear = 1970
  210. // Offsets to convert between internal and absolute or Unix times.
  211. absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay
  212. internalToAbsolute = -absoluteToInternal
  213. unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
  214. internalToUnix int64 = -unixToInternal
  215. )
  216. // IsZero reports whether t represents the zero time instant,
  217. // January 1, year 1, 00:00:00 UTC.
  218. func (t Time) IsZero() bool {
  219. return t.sec == 0 && t.nsec == 0
  220. }
  221. // abs returns the time t as an absolute time, adjusted by the zone offset.
  222. // It is called when computing a presentation property like Month or Hour.
  223. func (t Time) abs() uint64 {
  224. l := t.loc
  225. // Avoid function calls when possible.
  226. if l == nil || l == &localLoc {
  227. l = l.get()
  228. }
  229. sec := t.sec + internalToUnix
  230. if l != &utcLoc {
  231. if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
  232. sec += int64(l.cacheZone.offset)
  233. } else {
  234. _, offset, _, _, _ := l.lookup(sec)
  235. sec += int64(offset)
  236. }
  237. }
  238. return uint64(sec + (unixToInternal + internalToAbsolute))
  239. }
  240. // locabs is a combination of the Zone and abs methods,
  241. // extracting both return values from a single zone lookup.
  242. func (t Time) locabs() (name string, offset int, abs uint64) {
  243. l := t.loc
  244. if l == nil || l == &localLoc {
  245. l = l.get()
  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. name = l.cacheZone.name
  252. offset = l.cacheZone.offset
  253. } else {
  254. name, offset, _, _, _ = l.lookup(sec)
  255. }
  256. sec += int64(offset)
  257. } else {
  258. name = "UTC"
  259. }
  260. abs = uint64(sec + (unixToInternal + internalToAbsolute))
  261. return
  262. }
  263. // Date returns the year, month, and day in which t occurs.
  264. func (t Time) Date() (year int, month Month, day int) {
  265. year, month, day, _ = t.date(true)
  266. return
  267. }
  268. // Year returns the year in which t occurs.
  269. func (t Time) Year() int {
  270. year, _, _, _ := t.date(false)
  271. return year
  272. }
  273. // Month returns the month of the year specified by t.
  274. func (t Time) Month() Month {
  275. _, month, _, _ := t.date(true)
  276. return month
  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. // Weekday returns the day of the week specified by t.
  284. func (t Time) Weekday() Weekday {
  285. return absWeekday(t.abs())
  286. }
  287. // absWeekday is like Weekday but operates on an absolute time.
  288. func absWeekday(abs uint64) Weekday {
  289. // January 1 of the absolute year, like January 1 of 2001, was a Monday.
  290. sec := (abs + uint64(Monday)*secondsPerDay) % secondsPerWeek
  291. return Weekday(int(sec) / secondsPerDay)
  292. }
  293. // ISOWeek returns the ISO 8601 year and week number in which t occurs.
  294. // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to
  295. // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1
  296. // of year n+1.
  297. func (t Time) ISOWeek() (year, week int) {
  298. year, month, day, yday := t.date(true)
  299. wday := int(t.Weekday()+6) % 7 // weekday but Monday = 0.
  300. const (
  301. Mon int = iota
  302. Tue
  303. Wed
  304. Thu
  305. Fri
  306. Sat
  307. Sun
  308. )
  309. // Calculate week as number of Mondays in year up to
  310. // and including today, plus 1 because the first week is week 0.
  311. // Putting the + 1 inside the numerator as a + 7 keeps the
  312. // numerator from being negative, which would cause it to
  313. // round incorrectly.
  314. week = (yday - wday + 7) / 7
  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. // If the week number is still 0, we're in early January but in
  324. // the last week of last year.
  325. if week == 0 {
  326. year--
  327. week = 52
  328. // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday,
  329. // meaning Jan 1 of the next year is a Friday
  330. // or it was a leap year and Jan 1 of the next year is a Saturday.
  331. if jan1wday == Fri || (jan1wday == Sat && isLeap(year)) {
  332. week++
  333. }
  334. }
  335. // December 29 to 31 are in week 1 of next year if
  336. // they are after the last Thursday of the year and
  337. // December 31 is a Monday, Tuesday, or Wednesday.
  338. if month == December && day >= 29 && wday < Thu {
  339. if dec31wday := (wday + 31 - day) % 7; Mon <= dec31wday && dec31wday <= Wed {
  340. year++
  341. week = 1
  342. }
  343. }
  344. return
  345. }
  346. // Clock returns the hour, minute, and second within the day specified by t.
  347. func (t Time) Clock() (hour, min, sec int) {
  348. return absClock(t.abs())
  349. }
  350. // absClock is like clock but operates on an absolute time.
  351. func absClock(abs uint64) (hour, min, sec int) {
  352. sec = int(abs % secondsPerDay)
  353. hour = sec / secondsPerHour
  354. sec -= hour * secondsPerHour
  355. min = sec / secondsPerMinute
  356. sec -= min * secondsPerMinute
  357. return
  358. }
  359. // Hour returns the hour within the day specified by t, in the range [0, 23].
  360. func (t Time) Hour() int {
  361. return int(t.abs()%secondsPerDay) / secondsPerHour
  362. }
  363. // Minute returns the minute offset within the hour specified by t, in the range [0, 59].
  364. func (t Time) Minute() int {
  365. return int(t.abs()%secondsPerHour) / secondsPerMinute
  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. // Nanosecond returns the nanosecond offset within the second specified by t,
  372. // in the range [0, 999999999].
  373. func (t Time) Nanosecond() int {
  374. return int(t.nsec)
  375. }
  376. // YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years,
  377. // and [1,366] in leap years.
  378. func (t Time) YearDay() int {
  379. _, _, _, yday := t.date(false)
  380. return yday + 1
  381. }
  382. // A Duration represents the elapsed time between two instants
  383. // as an int64 nanosecond count. The representation limits the
  384. // largest representable duration to approximately 290 years.
  385. type Duration int64
  386. const (
  387. minDuration Duration = -1 << 63
  388. maxDuration Duration = 1<<63 - 1
  389. )
  390. // Common durations. There is no definition for units of Day or larger
  391. // to avoid confusion across daylight savings time zone transitions.
  392. //
  393. // To count the number of units in a Duration, divide:
  394. // second := time.Second
  395. // fmt.Print(int64(second/time.Millisecond)) // prints 1000
  396. //
  397. // To convert an integer number of units to a Duration, multiply:
  398. // seconds := 10
  399. // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
  400. //
  401. const (
  402. Nanosecond Duration = 1
  403. Microsecond = 1000 * Nanosecond
  404. Millisecond = 1000 * Microsecond
  405. Second = 1000 * Millisecond
  406. Minute = 60 * Second
  407. Hour = 60 * Minute
  408. )
  409. // String returns a string representing the duration in the form "72h3m0.5s".
  410. // Leading zero units are omitted. As a special case, durations less than one
  411. // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure
  412. // that the leading digit is non-zero. The zero duration formats as 0,
  413. // with no unit.
  414. func (d Duration) String() string {
  415. // Largest time is 2540400h10m10.000000000s
  416. var buf [32]byte
  417. w := len(buf)
  418. u := uint64(d)
  419. neg := d < 0
  420. if neg {
  421. u = -u
  422. }
  423. if u < uint64(Second) {
  424. // Special case: if duration is smaller than a second,
  425. // use smaller units, like 1.2ms
  426. var prec int
  427. w--
  428. buf[w] = 's'
  429. w--
  430. switch {
  431. case u == 0:
  432. return "0"
  433. case u < uint64(Microsecond):
  434. // print nanoseconds
  435. prec = 0
  436. buf[w] = 'n'
  437. case u < uint64(Millisecond):
  438. // print microseconds
  439. prec = 3
  440. // U+00B5 'µ' micro sign == 0xC2 0xB5
  441. w-- // Need room for two bytes.
  442. copy(buf[w:], "µ")
  443. default:
  444. // print milliseconds
  445. prec = 6
  446. buf[w] = 'm'
  447. }
  448. w, u = fmtFrac(buf[:w], u, prec)
  449. w = fmtInt(buf[:w], u)
  450. } else {
  451. w--
  452. buf[w] = 's'
  453. w, u = fmtFrac(buf[:w], u, 9)
  454. // u is now integer seconds
  455. w = fmtInt(buf[:w], u%60)
  456. u /= 60
  457. // u is now integer minutes
  458. if u > 0 {
  459. w--
  460. buf[w] = 'm'
  461. w = fmtInt(buf[:w], u%60)
  462. u /= 60
  463. // u is now integer hours
  464. // Stop at hours because days can be different lengths.
  465. if u > 0 {
  466. w--
  467. buf[w] = 'h'
  468. w = fmtInt(buf[:w], u)
  469. }
  470. }
  471. }
  472. if neg {
  473. w--
  474. buf[w] = '-'
  475. }
  476. return string(buf[w:])
  477. }
  478. // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
  479. // tail of buf, omitting trailing zeros. it omits the decimal
  480. // point too when the fraction is 0. It returns the index where the
  481. // output bytes begin and the value v/10**prec.
  482. func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
  483. // Omit trailing zeros up to and including decimal point.
  484. w := len(buf)
  485. print := false
  486. for i := 0; i < prec; i++ {
  487. digit := v % 10
  488. print = print || digit != 0
  489. if print {
  490. w--
  491. buf[w] = byte(digit) + '0'
  492. }
  493. v /= 10
  494. }
  495. if print {
  496. w--
  497. buf[w] = '.'
  498. }
  499. return w, v
  500. }
  501. // fmtInt formats v into the tail of buf.
  502. // It returns the index where the output begins.
  503. func fmtInt(buf []byte, v uint64) int {
  504. w := len(buf)
  505. if v == 0 {
  506. w--
  507. buf[w] = '0'
  508. } else {
  509. for v > 0 {
  510. w--
  511. buf[w] = byte(v%10) + '0'
  512. v /= 10
  513. }
  514. }
  515. return w
  516. }
  517. // Nanoseconds returns the duration as an integer nanosecond count.
  518. func (d Duration) Nanoseconds() int64 { return int64(d) }
  519. // These methods return float64 because the dominant
  520. // use case is for printing a floating point number like 1.5s, and
  521. // a truncation to integer would make them not useful in those cases.
  522. // Splitting the integer and fraction ourselves guarantees that
  523. // converting the returned float64 to an integer rounds the same
  524. // way that a pure integer conversion would have, even in cases
  525. // where, say, float64(d.Nanoseconds())/1e9 would have rounded
  526. // differently.
  527. // Seconds returns the duration as a floating point number of seconds.
  528. func (d Duration) Seconds() float64 {
  529. sec := d / Second
  530. nsec := d % Second
  531. return float64(sec) + float64(nsec)*1e-9
  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. // Hours returns the duration as a floating point number of hours.
  540. func (d Duration) Hours() float64 {
  541. hour := d / Hour
  542. nsec := d % Hour
  543. return float64(hour) + float64(nsec)*(1e-9/60/60)
  544. }
  545. // Add returns the time t+d.
  546. func (t Time) Add(d Duration) Time {
  547. t.sec += int64(d / 1e9)
  548. nsec := int32(t.nsec) + int32(d%1e9)
  549. if nsec >= 1e9 {
  550. t.sec++
  551. nsec -= 1e9
  552. } else if nsec < 0 {
  553. t.sec--
  554. nsec += 1e9
  555. }
  556. t.nsec = nsec
  557. return t
  558. }
  559. // Sub returns the duration t-u. If the result exceeds the maximum (or minimum)
  560. // value that can be stored in a Duration, the maximum (or minimum) duration
  561. // will be returned.
  562. // To compute t-d for a duration d, use t.Add(-d).
  563. func (t Time) Sub(u Time) Duration {
  564. d := Duration(t.sec-u.sec)*Second + Duration(int32(t.nsec)-int32(u.nsec))
  565. // Check for overflow or underflow.
  566. switch {
  567. case u.Add(d).Equal(t):
  568. return d // d is correct
  569. case t.Before(u):
  570. return minDuration // t - u is negative out of range
  571. default:
  572. return maxDuration // t - u is positive out of range
  573. }
  574. }
  575. // Since returns the time elapsed since t.
  576. // It is shorthand for time.Now().Sub(t).
  577. func Since(t Time) Duration {
  578. return Now().Sub(t)
  579. }
  580. // AddDate returns the time corresponding to adding the
  581. // given number of years, months, and days to t.
  582. // For example, AddDate(-1, 2, 3) applied to January 1, 2011
  583. // returns March 4, 2010.
  584. //
  585. // AddDate normalizes its result in the same way that Date does,
  586. // so, for example, adding one month to October 31 yields
  587. // December 1, the normalized form for November 31.
  588. func (t Time) AddDate(years int, months int, days int) Time {
  589. year, month, day := t.Date()
  590. hour, min, sec := t.Clock()
  591. return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec), t.loc)
  592. }
  593. const (
  594. secondsPerMinute = 60
  595. secondsPerHour = 60 * 60
  596. secondsPerDay = 24 * secondsPerHour
  597. secondsPerWeek = 7 * secondsPerDay
  598. daysPer400Years = 365*400 + 97
  599. daysPer100Years = 365*100 + 24
  600. daysPer4Years = 365*4 + 1
  601. )
  602. // date computes the year, day of year, and when full=true,
  603. // the month and day in which t occurs.
  604. func (t Time) date(full bool) (year int, month Month, day int, yday int) {
  605. return absDate(t.abs(), full)
  606. }
  607. // absDate is like date but operates on an absolute time.
  608. func absDate(abs uint64, full bool) (year int, month Month, day int, yday int) {
  609. // Split into time and day.
  610. d := abs / secondsPerDay
  611. // Account for 400 year cycles.
  612. n := d / daysPer400Years
  613. y := 400 * n
  614. d -= daysPer400Years * n
  615. // Cut off 100-year cycles.
  616. // The last cycle has one extra leap year, so on the last day
  617. // of that year, day / daysPer100Years will be 4 instead of 3.
  618. // Cut it back down to 3 by subtracting n>>2.
  619. n = d / daysPer100Years
  620. n -= n >> 2
  621. y += 100 * n
  622. d -= daysPer100Years * n
  623. // Cut off 4-year cycles.
  624. // The last cycle has a missing leap year, which does not
  625. // affect the computation.
  626. n = d / daysPer4Years
  627. y += 4 * n
  628. d -= daysPer4Years * n
  629. // Cut off years within a 4-year cycle.
  630. // The last year is a leap year, so on the last day of that year,
  631. // day / 365 will be 4 instead of 3. Cut it back down to 3
  632. // by subtracting n>>2.
  633. n = d / 365
  634. n -= n >> 2
  635. y += n
  636. d -= 365 * n
  637. year = int(int64(y) + absoluteZeroYear)
  638. yday = int(d)
  639. if !full {
  640. return
  641. }
  642. day = yday
  643. if isLeap(year) {
  644. // Leap year
  645. switch {
  646. case day > 31+29-1:
  647. // After leap day; pretend it wasn't there.
  648. day--
  649. case day == 31+29-1:
  650. // Leap day.
  651. month = February
  652. day = 29
  653. return
  654. }
  655. }
  656. // Estimate month on assumption that every month has 31 days.
  657. // The estimate may be too low by at most one month, so adjust.
  658. month = Month(day / 31)
  659. end := int(daysBefore[month+1])
  660. var begin int
  661. if day >= end {
  662. month++
  663. begin = end
  664. } else {
  665. begin = int(daysBefore[month])
  666. }
  667. month++ // because January is 1
  668. day = day - begin + 1
  669. return
  670. }
  671. // daysBefore[m] counts the number of days in a non-leap year
  672. // before month m begins. There is an entry for m=12, counting
  673. // the number of days before January of next year (365).
  674. var daysBefore = [...]int32{
  675. 0,
  676. 31,
  677. 31 + 28,
  678. 31 + 28 + 31,
  679. 31 + 28 + 31 + 30,
  680. 31 + 28 + 31 + 30 + 31,
  681. 31 + 28 + 31 + 30 + 31 + 30,
  682. 31 + 28 + 31 + 30 + 31 + 30 + 31,
  683. 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
  684. 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
  685. 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
  686. 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
  687. 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31,
  688. }
  689. func daysIn(m Month, year int) int {
  690. if m == February && isLeap(year) {
  691. return 29
  692. }
  693. return int(daysBefore[m] - daysBefore[m-1])
  694. }
  695. // Provided by package runtime.
  696. func now() (sec int64, nsec int32)
  697. // Now returns the current local time.
  698. func Now() Time {
  699. sec, nsec := now()
  700. return Time{sec + unixToInternal, nsec, Local}
  701. }
  702. // UTC returns t with the location set to UTC.
  703. func (t Time) UTC() Time {
  704. t.loc = UTC
  705. return t
  706. }
  707. // Local returns t with the location set to local time.
  708. func (t Time) Local() Time {
  709. t.loc = Local
  710. return t
  711. }
  712. // In returns t with the location information set to loc.
  713. //
  714. // In panics if loc is nil.
  715. func (t Time) In(loc *Location) Time {
  716. if loc == nil {
  717. panic("time: missing Location in call to Time.In")
  718. }
  719. t.loc = loc
  720. return t
  721. }
  722. // Location returns the time zone information associated with t.
  723. func (t Time) Location() *Location {
  724. l := t.loc
  725. if l == nil {
  726. l = UTC
  727. }
  728. return l
  729. }
  730. // Zone computes the time zone in effect at time t, returning the abbreviated
  731. // name of the zone (such as "CET") and its offset in seconds east of UTC.
  732. func (t Time) Zone() (name string, offset int) {
  733. name, offset, _, _, _ = t.loc.lookup(t.sec + internalToUnix)
  734. return
  735. }
  736. // Unix returns t as a Unix time, the number of seconds elapsed
  737. // since January 1, 1970 UTC.
  738. func (t Time) Unix() int64 {
  739. return t.sec + internalToUnix
  740. }
  741. // UnixNano returns t as a Unix time, the number of nanoseconds elapsed
  742. // since January 1, 1970 UTC. The result is undefined if the Unix time
  743. // in nanoseconds cannot be represented by an int64. Note that this
  744. // means the result of calling UnixNano on the zero Time is undefined.
  745. func (t Time) UnixNano() int64 {
  746. return (t.sec+internalToUnix)*1e9 + int64(t.nsec)
  747. }
  748. const timeBinaryVersion byte = 1
  749. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  750. func (t Time) MarshalBinary() ([]byte, error) {
  751. var offsetMin int16 // minutes east of UTC. -1 is UTC.
  752. if t.Location() == &utcLoc {
  753. offsetMin = -1
  754. } else {
  755. _, offset := t.Zone()
  756. if offset%60 != 0 {
  757. return nil, errors.New("Time.MarshalBinary: zone offset has fractional minute")
  758. }
  759. offset /= 60
  760. if offset < -32768 || offset == -1 || offset > 32767 {
  761. return nil, errors.New("Time.MarshalBinary: unexpected zone offset")
  762. }
  763. offsetMin = int16(offset)
  764. }
  765. enc := []byte{
  766. timeBinaryVersion, // byte 0 : version
  767. byte(t.sec >> 56), // bytes 1-8: seconds
  768. byte(t.sec >> 48),
  769. byte(t.sec >> 40),
  770. byte(t.sec >> 32),
  771. byte(t.sec >> 24),
  772. byte(t.sec >> 16),
  773. byte(t.sec >> 8),
  774. byte(t.sec),
  775. byte(t.nsec >> 24), // bytes 9-12: nanoseconds
  776. byte(t.nsec >> 16),
  777. byte(t.nsec >> 8),
  778. byte(t.nsec),
  779. byte(offsetMin >> 8), // bytes 13-14: zone offset in minutes
  780. byte(offsetMin),
  781. }
  782. return enc, nil
  783. }
  784. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  785. func (t *Time) UnmarshalBinary(data []byte) error {
  786. buf := data
  787. if len(buf) == 0 {
  788. return errors.New("Time.UnmarshalBinary: no data")
  789. }
  790. if buf[0] != timeBinaryVersion {
  791. return errors.New("Time.UnmarshalBinary: unsupported version")
  792. }
  793. if len(buf) != /*version*/ 1+ /*sec*/ 8+ /*nsec*/ 4+ /*zone offset*/ 2 {
  794. return errors.New("Time.UnmarshalBinary: invalid length")
  795. }
  796. buf = buf[1:]
  797. t.sec = int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 |
  798. int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56
  799. buf = buf[8:]
  800. t.nsec = int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24
  801. buf = buf[4:]
  802. offset := int(int16(buf[1])|int16(buf[0])<<8) * 60
  803. if offset == -1*60 {
  804. t.loc = &utcLoc
  805. } else if _, localoff, _, _, _ := Local.lookup(t.sec + internalToUnix); offset == localoff {
  806. t.loc = Local
  807. } else {
  808. t.loc = FixedZone("", offset)
  809. }
  810. return nil
  811. }
  812. // TODO(rsc): Remove GobEncoder, GobDecoder, MarshalJSON, UnmarshalJSON in Go 2.
  813. // The same semantics will be provided by the generic MarshalBinary, MarshalText,
  814. // UnmarshalBinary, UnmarshalText.
  815. // GobEncode implements the gob.GobEncoder interface.
  816. func (t Time) GobEncode() ([]byte, error) {
  817. return t.MarshalBinary()
  818. }
  819. // GobDecode implements the gob.GobDecoder interface.
  820. func (t *Time) GobDecode(data []byte) error {
  821. return t.UnmarshalBinary(data)
  822. }
  823. // MarshalJSON implements the json.Marshaler interface.
  824. // The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
  825. func (t Time) MarshalJSON() ([]byte, error) {
  826. if y := t.Year(); y < 0 || y >= 10000 {
  827. // RFC 3339 is clear that years are 4 digits exactly.
  828. // See golang.org/issue/4556#c15 for more discussion.
  829. return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
  830. }
  831. return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil
  832. }
  833. // UnmarshalJSON implements the json.Unmarshaler interface.
  834. // The time is expected to be a quoted string in RFC 3339 format.
  835. func (t *Time) UnmarshalJSON(data []byte) (err error) {
  836. // Fractional seconds are handled implicitly by Parse.
  837. *t, err = Parse(`"`+RFC3339+`"`, string(data))
  838. return
  839. }
  840. // MarshalText implements the encoding.TextMarshaler interface.
  841. // The time is formatted in RFC 3339 format, with sub-second precision added if present.
  842. func (t Time) MarshalText() ([]byte, error) {
  843. if y := t.Year(); y < 0 || y >= 10000 {
  844. return nil, errors.New("Time.MarshalText: year outside of range [0,9999]")
  845. }
  846. return []byte(t.Format(RFC3339Nano)), nil
  847. }
  848. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  849. // The time is expected to be in RFC 3339 format.
  850. func (t *Time) UnmarshalText(data []byte) (err error) {
  851. // Fractional seconds are handled implicitly by Parse.
  852. *t, err = Parse(RFC3339, string(data))
  853. return
  854. }
  855. // Unix returns the local Time corresponding to the given Unix time,
  856. // sec seconds and nsec nanoseconds since January 1, 1970 UTC.
  857. // It is valid to pass nsec outside the range [0, 999999999].
  858. func Unix(sec int64, nsec int64) Time {
  859. if nsec < 0 || nsec >= 1e9 {
  860. n := nsec / 1e9
  861. sec += n
  862. nsec -= n * 1e9
  863. if nsec < 0 {
  864. nsec += 1e9
  865. sec--
  866. }
  867. }
  868. return Time{sec + unixToInternal, int32(nsec), Local}
  869. }
  870. func isLeap(year int) bool {
  871. return year%4 == 0 && (year%100 != 0 || year%400 == 0)
  872. }
  873. // norm returns nhi, nlo such that
  874. // hi * base + lo == nhi * base + nlo
  875. // 0 <= nlo < base
  876. func norm(hi, lo, base int) (nhi, nlo int) {
  877. if lo < 0 {
  878. n := (-lo-1)/base + 1
  879. hi -= n
  880. lo += n * base
  881. }
  882. if lo >= base {
  883. n := lo / base
  884. hi += n
  885. lo -= n * base
  886. }
  887. return hi, lo
  888. }
  889. // Date returns the Time corresponding to
  890. // yyyy-mm-dd hh:mm:ss + nsec nanoseconds
  891. // in the appropriate zone for that time in the given location.
  892. //
  893. // The month, day, hour, min, sec, and nsec values may be outside
  894. // their usual ranges and will be normalized during the conversion.
  895. // For example, October 32 converts to November 1.
  896. //
  897. // A daylight savings time transition skips or repeats times.
  898. // For example, in the United States, March 13, 2011 2:15am never occurred,
  899. // while November 6, 2011 1:15am occurred twice. In such cases, the
  900. // choice of time zone, and therefore the time, is not well-defined.
  901. // Date returns a time that is correct in one of the two zones involved
  902. // in the transition, but it does not guarantee which.
  903. //
  904. // Date panics if loc is nil.
  905. func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time {
  906. if loc == nil {
  907. panic("time: missing Location in call to Date")
  908. }
  909. // Normalize month, overflowing into year.
  910. m := int(month) - 1
  911. year, m = norm(year, m, 12)
  912. month = Month(m) + 1
  913. // Normalize nsec, sec, min, hour, overflowing into day.
  914. sec, nsec = norm(sec, nsec, 1e9)
  915. min, sec = norm(min, sec, 60)
  916. hour, min = norm(hour, min, 60)
  917. day, hour = norm(day, hour, 24)
  918. y := uint64(int64(year) - absoluteZeroYear)
  919. // Compute days since the absolute epoch.
  920. // Add in days from 400-year cycles.
  921. n := y / 400
  922. y -= 400 * n
  923. d := daysPer400Years * n
  924. // Add in 100-year cycles.
  925. n = y / 100
  926. y -= 100 * n
  927. d += daysPer100Years * n
  928. // Add in 4-year cycles.
  929. n = y / 4
  930. y -= 4 * n
  931. d += daysPer4Years * n
  932. // Add in non-leap years.
  933. n = y
  934. d += 365 * n
  935. // Add in days before this month.
  936. d += uint64(daysBefore[month-1])
  937. if isLeap(year) && month >= March {
  938. d++ // February 29
  939. }
  940. // Add in days before today.
  941. d += uint64(day - 1)
  942. // Add in time elapsed today.
  943. abs := d * secondsPerDay
  944. abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec)
  945. unix := int64(abs) + (absoluteToInternal + internalToUnix)
  946. // Look for zone offset for t, so we can adjust to UTC.
  947. // The lookup function expects UTC, so we pass t in the
  948. // hope that it will not be too close to a zone transition,
  949. // and then adjust if it is.
  950. _, offset, _, start, end := loc.lookup(unix)
  951. if offset != 0 {
  952. switch utc := unix - int64(offset); {
  953. case utc < start:
  954. _, offset, _, _, _ = loc.lookup(start - 1)
  955. case utc >= end:
  956. _, offset, _, _, _ = loc.lookup(end)
  957. }
  958. unix -= int64(offset)
  959. }
  960. return Time{unix + unixToInternal, int32(nsec), loc}
  961. }
  962. // Truncate returns the result of rounding t down to a multiple of d (since the zero time).
  963. // If d <= 0, Truncate returns t unchanged.
  964. func (t Time) Truncate(d Duration) Time {
  965. if d <= 0 {
  966. return t
  967. }
  968. _, r := div(t, d)
  969. return t.Add(-r)
  970. }
  971. // Round returns the result of rounding t to the nearest multiple of d (since the zero time).
  972. // The rounding behavior for halfway values is to round up.
  973. // If d <= 0, Round returns t unchanged.
  974. func (t Time) Round(d Duration) Time {
  975. if d <= 0 {
  976. return t
  977. }
  978. _, r := div(t, d)
  979. if r+r < d {
  980. return t.Add(-r)
  981. }
  982. return t.Add(d - r)
  983. }
  984. // div divides t by d and returns the quotient parity and remainder.
  985. // We don't use the quotient parity anymore (round half up instead of round to even)
  986. // but it's still here in case we change our minds.
  987. func div(t Time, d Duration) (qmod2 int, r Duration) {
  988. neg := false
  989. nsec := int32(t.nsec)
  990. if t.sec < 0 {
  991. // Operate on absolute value.
  992. neg = true
  993. t.sec = -t.sec
  994. nsec = -nsec
  995. if nsec < 0 {
  996. nsec += 1e9
  997. t.sec-- // t.sec >= 1 before the -- so safe
  998. }
  999. }
  1000. switch {
  1001. // Special case: 2d divides 1 second.
  1002. case d < Second && Second%(d+d) == 0:
  1003. qmod2 = int(nsec/int32(d)) & 1
  1004. r = Duration(nsec % int32(d))
  1005. // Special case: d is a multiple of 1 second.
  1006. case d%Second == 0:
  1007. d1 := int64(d / Second)
  1008. qmod2 = int(t.sec/d1) & 1
  1009. r = Duration(t.sec%d1)*Second + Duration(nsec)
  1010. // General case.
  1011. // This could be faster if more cleverness were applied,
  1012. // but it's really only here to avoid special case restrictions in the API.
  1013. // No one will care about these cases.
  1014. default:
  1015. // Compute nanoseconds as 128-bit number.
  1016. sec := uint64(t.sec)
  1017. tmp := (sec >> 32) * 1e9
  1018. u1 := tmp >> 32
  1019. u0 := tmp << 32
  1020. tmp = uint64(sec&0xFFFFFFFF) * 1e9
  1021. u0x, u0 := u0, u0+tmp
  1022. if u0 < u0x {
  1023. u1++
  1024. }
  1025. u0x, u0 = u0, u0+uint64(nsec)
  1026. if u0 < u0x {
  1027. u1++
  1028. }
  1029. // Compute remainder by subtracting r<<k for decreasing k.
  1030. // Quotient parity is whether we subtract on last round.
  1031. d1 := uint64(d)
  1032. for d1>>63 != 1 {
  1033. d1 <<= 1
  1034. }
  1035. d0 := uint64(0)
  1036. for {
  1037. qmod2 = 0
  1038. if u1 > d1 || u1 == d1 && u0 >= d0 {
  1039. // subtract
  1040. qmod2 = 1
  1041. u0x, u0 = u0, u0-d0
  1042. if u0 > u0x {
  1043. u1--
  1044. }
  1045. u1 -= d1
  1046. }
  1047. if d1 == 0 && d0 == uint64(d) {
  1048. break
  1049. }
  1050. d0 >>= 1
  1051. d0 |= (d1 & 1) << 63
  1052. d1 >>= 1
  1053. }
  1054. r = Duration(u0)
  1055. }
  1056. if neg && r != 0 {
  1057. // If input was negative and not an exact multiple of d, we computed q, r such that
  1058. // q*d + r = -t
  1059. // But the right answers are given by -(q-1), d-r:
  1060. // q*d + r = -t
  1061. // -q*d - r = t
  1062. // -(q-1)*d + (d - r) = t
  1063. qmod2 ^= 1
  1064. r = d - r
  1065. }
  1066. return
  1067. }