format.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. // Copyright 2010 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
  5. import "errors"
  6. // These are predefined layouts for use in Time.Format and Time.Parse.
  7. // The reference time used in the layouts is the specific time:
  8. // Mon Jan 2 15:04:05 MST 2006
  9. // which is Unix time 1136239445. Since MST is GMT-0700,
  10. // the reference time can be thought of as
  11. // 01/02 03:04:05PM '06 -0700
  12. // To define your own format, write down what the reference time would look
  13. // like formatted your way; see the values of constants like ANSIC,
  14. // StampMicro or Kitchen for examples. The model is to demonstrate what the
  15. // reference time looks like so that the Format and Parse methods can apply
  16. // the same transformation to a general time value.
  17. //
  18. // Within the format string, an underscore _ represents a space that may be
  19. // replaced by a digit if the following number (a day) has two digits; for
  20. // compatibility with fixed-width Unix time formats.
  21. //
  22. // A decimal point followed by one or more zeros represents a fractional
  23. // second, printed to the given number of decimal places. A decimal point
  24. // followed by one or more nines represents a fractional second, printed to
  25. // the given number of decimal places, with trailing zeros removed.
  26. // When parsing (only), the input may contain a fractional second
  27. // field immediately after the seconds field, even if the layout does not
  28. // signify its presence. In that case a decimal point followed by a maximal
  29. // series of digits is parsed as a fractional second.
  30. //
  31. // Numeric time zone offsets format as follows:
  32. // -0700 ±hhmm
  33. // -07:00 ±hh:mm
  34. // Replacing the sign in the format with a Z triggers
  35. // the ISO 8601 behavior of printing Z instead of an
  36. // offset for the UTC zone. Thus:
  37. // Z0700 Z or ±hhmm
  38. // Z07:00 Z or ±hh:mm
  39. const (
  40. ANSIC = "Mon Jan _2 15:04:05 2006"
  41. UnixDate = "Mon Jan _2 15:04:05 MST 2006"
  42. RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
  43. RFC822 = "02 Jan 06 15:04 MST"
  44. RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
  45. RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
  46. RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
  47. RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
  48. RFC3339 = "2006-01-02T15:04:05Z07:00"
  49. RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
  50. Kitchen = "3:04PM"
  51. // Handy time stamps.
  52. Stamp = "Jan _2 15:04:05"
  53. StampMilli = "Jan _2 15:04:05.000"
  54. StampMicro = "Jan _2 15:04:05.000000"
  55. StampNano = "Jan _2 15:04:05.000000000"
  56. )
  57. const (
  58. _ = iota
  59. stdLongMonth = iota + stdNeedDate // "January"
  60. stdMonth // "Jan"
  61. stdNumMonth // "1"
  62. stdZeroMonth // "01"
  63. stdLongWeekDay // "Monday"
  64. stdWeekDay // "Mon"
  65. stdDay // "2"
  66. stdUnderDay // "_2"
  67. stdZeroDay // "02"
  68. stdHour = iota + stdNeedClock // "15"
  69. stdHour12 // "3"
  70. stdZeroHour12 // "03"
  71. stdMinute // "4"
  72. stdZeroMinute // "04"
  73. stdSecond // "5"
  74. stdZeroSecond // "05"
  75. stdLongYear = iota + stdNeedDate // "2006"
  76. stdYear // "06"
  77. stdPM = iota + stdNeedClock // "PM"
  78. stdpm // "pm"
  79. stdTZ = iota // "MST"
  80. stdISO8601TZ // "Z0700" // prints Z for UTC
  81. stdISO8601SecondsTZ // "Z070000"
  82. stdISO8601ColonTZ // "Z07:00" // prints Z for UTC
  83. stdISO8601ColonSecondsTZ // "Z07:00:00"
  84. stdNumTZ // "-0700" // always numeric
  85. stdNumSecondsTz // "-070000"
  86. stdNumShortTZ // "-07" // always numeric
  87. stdNumColonTZ // "-07:00" // always numeric
  88. stdNumColonSecondsTZ // "-07:00:00"
  89. stdFracSecond0 // ".0", ".00", ... , trailing zeros included
  90. stdFracSecond9 // ".9", ".99", ..., trailing zeros omitted
  91. stdNeedDate = 1 << 8 // need month, day, year
  92. stdNeedClock = 2 << 8 // need hour, minute, second
  93. stdArgShift = 16 // extra argument in high bits, above low stdArgShift
  94. stdMask = 1<<stdArgShift - 1 // mask out argument
  95. )
  96. // std0x records the std values for "01", "02", ..., "06".
  97. var std0x = [...]int{stdZeroMonth, stdZeroDay, stdZeroHour12, stdZeroMinute, stdZeroSecond, stdYear}
  98. // startsWithLowerCase reports whether the string has a lower-case letter at the beginning.
  99. // Its purpose is to prevent matching strings like "Month" when looking for "Mon".
  100. func startsWithLowerCase(str string) bool {
  101. if len(str) == 0 {
  102. return false
  103. }
  104. c := str[0]
  105. return 'a' <= c && c <= 'z'
  106. }
  107. // nextStdChunk finds the first occurrence of a std string in
  108. // layout and returns the text before, the std string, and the text after.
  109. func nextStdChunk(layout string) (prefix string, std int, suffix string) {
  110. for i := 0; i < len(layout); i++ {
  111. switch c := int(layout[i]); c {
  112. case 'J': // January, Jan
  113. if len(layout) >= i+3 && layout[i:i+3] == "Jan" {
  114. if len(layout) >= i+7 && layout[i:i+7] == "January" {
  115. return layout[0:i], stdLongMonth, layout[i+7:]
  116. }
  117. if !startsWithLowerCase(layout[i+3:]) {
  118. return layout[0:i], stdMonth, layout[i+3:]
  119. }
  120. }
  121. case 'M': // Monday, Mon, MST
  122. if len(layout) >= i+3 {
  123. if layout[i:i+3] == "Mon" {
  124. if len(layout) >= i+6 && layout[i:i+6] == "Monday" {
  125. return layout[0:i], stdLongWeekDay, layout[i+6:]
  126. }
  127. if !startsWithLowerCase(layout[i+3:]) {
  128. return layout[0:i], stdWeekDay, layout[i+3:]
  129. }
  130. }
  131. if layout[i:i+3] == "MST" {
  132. return layout[0:i], stdTZ, layout[i+3:]
  133. }
  134. }
  135. case '0': // 01, 02, 03, 04, 05, 06
  136. if len(layout) >= i+2 && '1' <= layout[i+1] && layout[i+1] <= '6' {
  137. return layout[0:i], std0x[layout[i+1]-'1'], layout[i+2:]
  138. }
  139. case '1': // 15, 1
  140. if len(layout) >= i+2 && layout[i+1] == '5' {
  141. return layout[0:i], stdHour, layout[i+2:]
  142. }
  143. return layout[0:i], stdNumMonth, layout[i+1:]
  144. case '2': // 2006, 2
  145. if len(layout) >= i+4 && layout[i:i+4] == "2006" {
  146. return layout[0:i], stdLongYear, layout[i+4:]
  147. }
  148. return layout[0:i], stdDay, layout[i+1:]
  149. case '_': // _2
  150. if len(layout) >= i+2 && layout[i+1] == '2' {
  151. return layout[0:i], stdUnderDay, layout[i+2:]
  152. }
  153. case '3':
  154. return layout[0:i], stdHour12, layout[i+1:]
  155. case '4':
  156. return layout[0:i], stdMinute, layout[i+1:]
  157. case '5':
  158. return layout[0:i], stdSecond, layout[i+1:]
  159. case 'P': // PM
  160. if len(layout) >= i+2 && layout[i+1] == 'M' {
  161. return layout[0:i], stdPM, layout[i+2:]
  162. }
  163. case 'p': // pm
  164. if len(layout) >= i+2 && layout[i+1] == 'm' {
  165. return layout[0:i], stdpm, layout[i+2:]
  166. }
  167. case '-': // -070000, -07:00:00, -0700, -07:00, -07
  168. if len(layout) >= i+7 && layout[i:i+7] == "-070000" {
  169. return layout[0:i], stdNumSecondsTz, layout[i+7:]
  170. }
  171. if len(layout) >= i+9 && layout[i:i+9] == "-07:00:00" {
  172. return layout[0:i], stdNumColonSecondsTZ, layout[i+9:]
  173. }
  174. if len(layout) >= i+5 && layout[i:i+5] == "-0700" {
  175. return layout[0:i], stdNumTZ, layout[i+5:]
  176. }
  177. if len(layout) >= i+6 && layout[i:i+6] == "-07:00" {
  178. return layout[0:i], stdNumColonTZ, layout[i+6:]
  179. }
  180. if len(layout) >= i+3 && layout[i:i+3] == "-07" {
  181. return layout[0:i], stdNumShortTZ, layout[i+3:]
  182. }
  183. case 'Z': // Z070000, Z07:00:00, Z0700, Z07:00,
  184. if len(layout) >= i+7 && layout[i:i+7] == "Z070000" {
  185. return layout[0:i], stdISO8601SecondsTZ, layout[i+7:]
  186. }
  187. if len(layout) >= i+9 && layout[i:i+9] == "Z07:00:00" {
  188. return layout[0:i], stdISO8601ColonSecondsTZ, layout[i+9:]
  189. }
  190. if len(layout) >= i+5 && layout[i:i+5] == "Z0700" {
  191. return layout[0:i], stdISO8601TZ, layout[i+5:]
  192. }
  193. if len(layout) >= i+6 && layout[i:i+6] == "Z07:00" {
  194. return layout[0:i], stdISO8601ColonTZ, layout[i+6:]
  195. }
  196. case '.': // .000 or .999 - repeated digits for fractional seconds.
  197. if i+1 < len(layout) && (layout[i+1] == '0' || layout[i+1] == '9') {
  198. ch := layout[i+1]
  199. j := i + 1
  200. for j < len(layout) && layout[j] == ch {
  201. j++
  202. }
  203. // String of digits must end here - only fractional second is all digits.
  204. if !isDigit(layout, j) {
  205. std := stdFracSecond0
  206. if layout[i+1] == '9' {
  207. std = stdFracSecond9
  208. }
  209. std |= (j - (i + 1)) << stdArgShift
  210. return layout[0:i], std, layout[j:]
  211. }
  212. }
  213. }
  214. }
  215. return layout, 0, ""
  216. }
  217. var longDayNames = []string{
  218. "Sunday",
  219. "Monday",
  220. "Tuesday",
  221. "Wednesday",
  222. "Thursday",
  223. "Friday",
  224. "Saturday",
  225. }
  226. var shortDayNames = []string{
  227. "Sun",
  228. "Mon",
  229. "Tue",
  230. "Wed",
  231. "Thu",
  232. "Fri",
  233. "Sat",
  234. }
  235. var shortMonthNames = []string{
  236. "---",
  237. "Jan",
  238. "Feb",
  239. "Mar",
  240. "Apr",
  241. "May",
  242. "Jun",
  243. "Jul",
  244. "Aug",
  245. "Sep",
  246. "Oct",
  247. "Nov",
  248. "Dec",
  249. }
  250. var longMonthNames = []string{
  251. "---",
  252. "January",
  253. "February",
  254. "March",
  255. "April",
  256. "May",
  257. "June",
  258. "July",
  259. "August",
  260. "September",
  261. "October",
  262. "November",
  263. "December",
  264. }
  265. // match returns true if s1 and s2 match ignoring case.
  266. // It is assumed s1 and s2 are the same length.
  267. func match(s1, s2 string) bool {
  268. for i := 0; i < len(s1); i++ {
  269. c1 := s1[i]
  270. c2 := s2[i]
  271. if c1 != c2 {
  272. // Switch to lower-case; 'a'-'A' is known to be a single bit.
  273. c1 |= 'a' - 'A'
  274. c2 |= 'a' - 'A'
  275. if c1 != c2 || c1 < 'a' || c1 > 'z' {
  276. return false
  277. }
  278. }
  279. }
  280. return true
  281. }
  282. func lookup(tab []string, val string) (int, string, error) {
  283. for i, v := range tab {
  284. if len(val) >= len(v) && match(val[0:len(v)], v) {
  285. return i, val[len(v):], nil
  286. }
  287. }
  288. return -1, val, errBad
  289. }
  290. // appendUint appends the decimal form of x to b and returns the result.
  291. // If x is a single-digit number and pad != 0, appendUint inserts the pad byte
  292. // before the digit.
  293. // Duplicates functionality in strconv, but avoids dependency.
  294. func appendUint(b []byte, x uint, pad byte) []byte {
  295. if x < 10 {
  296. if pad != 0 {
  297. b = append(b, pad)
  298. }
  299. return append(b, byte('0'+x))
  300. }
  301. if x < 100 {
  302. b = append(b, byte('0'+x/10))
  303. b = append(b, byte('0'+x%10))
  304. return b
  305. }
  306. var buf [32]byte
  307. n := len(buf)
  308. if x == 0 {
  309. return append(b, '0')
  310. }
  311. for x >= 10 {
  312. n--
  313. buf[n] = byte(x%10 + '0')
  314. x /= 10
  315. }
  316. n--
  317. buf[n] = byte(x + '0')
  318. return append(b, buf[n:]...)
  319. }
  320. // Never printed, just needs to be non-nil for return by atoi.
  321. var atoiError = errors.New("time: invalid number")
  322. // Duplicates functionality in strconv, but avoids dependency.
  323. func atoi(s string) (x int, err error) {
  324. neg := false
  325. if s != "" && (s[0] == '-' || s[0] == '+') {
  326. neg = s[0] == '-'
  327. s = s[1:]
  328. }
  329. q, rem, err := leadingInt(s)
  330. x = int(q)
  331. if err != nil || rem != "" {
  332. return 0, atoiError
  333. }
  334. if neg {
  335. x = -x
  336. }
  337. return x, nil
  338. }
  339. // formatNano appends a fractional second, as nanoseconds, to b
  340. // and returns the result.
  341. func formatNano(b []byte, nanosec uint, n int, trim bool) []byte {
  342. u := nanosec
  343. var buf [9]byte
  344. for start := len(buf); start > 0; {
  345. start--
  346. buf[start] = byte(u%10 + '0')
  347. u /= 10
  348. }
  349. if n > 9 {
  350. n = 9
  351. }
  352. if trim {
  353. for n > 0 && buf[n-1] == '0' {
  354. n--
  355. }
  356. if n == 0 {
  357. return b
  358. }
  359. }
  360. b = append(b, '.')
  361. return append(b, buf[:n]...)
  362. }
  363. // String returns the time formatted using the format string
  364. // "2006-01-02 15:04:05.999999999 -0700 MST"
  365. func (t Time) String() string {
  366. return t.Format("2006-01-02 15:04:05.999999999 -0700 MST")
  367. }
  368. // Format returns a textual representation of the time value formatted
  369. // according to layout, which defines the format by showing how the reference
  370. // time, defined to be
  371. // Mon Jan 2 15:04:05 -0700 MST 2006
  372. // would be displayed if it were the value; it serves as an example of the
  373. // desired output. The same display rules will then be applied to the time
  374. // value.
  375. // Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard
  376. // and convenient representations of the reference time. For more information
  377. // about the formats and the definition of the reference time, see the
  378. // documentation for ANSIC and the other constants defined by this package.
  379. func (t Time) Format(layout string) string {
  380. var (
  381. name, offset, abs = t.locabs()
  382. year int = -1
  383. month Month
  384. day int
  385. hour int = -1
  386. min int
  387. sec int
  388. b []byte
  389. buf [64]byte
  390. )
  391. max := len(layout) + 10
  392. if max <= len(buf) {
  393. b = buf[:0]
  394. } else {
  395. b = make([]byte, 0, max)
  396. }
  397. // Each iteration generates one std value.
  398. for layout != "" {
  399. prefix, std, suffix := nextStdChunk(layout)
  400. if prefix != "" {
  401. b = append(b, prefix...)
  402. }
  403. if std == 0 {
  404. break
  405. }
  406. layout = suffix
  407. // Compute year, month, day if needed.
  408. if year < 0 && std&stdNeedDate != 0 {
  409. year, month, day, _ = absDate(abs, true)
  410. }
  411. // Compute hour, minute, second if needed.
  412. if hour < 0 && std&stdNeedClock != 0 {
  413. hour, min, sec = absClock(abs)
  414. }
  415. switch std & stdMask {
  416. case stdYear:
  417. y := year
  418. if y < 0 {
  419. y = -y
  420. }
  421. b = appendUint(b, uint(y%100), '0')
  422. case stdLongYear:
  423. // Pad year to at least 4 digits.
  424. y := year
  425. switch {
  426. case year <= -1000:
  427. b = append(b, '-')
  428. y = -y
  429. case year <= -100:
  430. b = append(b, "-0"...)
  431. y = -y
  432. case year <= -10:
  433. b = append(b, "-00"...)
  434. y = -y
  435. case year < 0:
  436. b = append(b, "-000"...)
  437. y = -y
  438. case year < 10:
  439. b = append(b, "000"...)
  440. case year < 100:
  441. b = append(b, "00"...)
  442. case year < 1000:
  443. b = append(b, '0')
  444. }
  445. b = appendUint(b, uint(y), 0)
  446. case stdMonth:
  447. b = append(b, month.String()[:3]...)
  448. case stdLongMonth:
  449. m := month.String()
  450. b = append(b, m...)
  451. case stdNumMonth:
  452. b = appendUint(b, uint(month), 0)
  453. case stdZeroMonth:
  454. b = appendUint(b, uint(month), '0')
  455. case stdWeekDay:
  456. b = append(b, absWeekday(abs).String()[:3]...)
  457. case stdLongWeekDay:
  458. s := absWeekday(abs).String()
  459. b = append(b, s...)
  460. case stdDay:
  461. b = appendUint(b, uint(day), 0)
  462. case stdUnderDay:
  463. b = appendUint(b, uint(day), ' ')
  464. case stdZeroDay:
  465. b = appendUint(b, uint(day), '0')
  466. case stdHour:
  467. b = appendUint(b, uint(hour), '0')
  468. case stdHour12:
  469. // Noon is 12PM, midnight is 12AM.
  470. hr := hour % 12
  471. if hr == 0 {
  472. hr = 12
  473. }
  474. b = appendUint(b, uint(hr), 0)
  475. case stdZeroHour12:
  476. // Noon is 12PM, midnight is 12AM.
  477. hr := hour % 12
  478. if hr == 0 {
  479. hr = 12
  480. }
  481. b = appendUint(b, uint(hr), '0')
  482. case stdMinute:
  483. b = appendUint(b, uint(min), 0)
  484. case stdZeroMinute:
  485. b = appendUint(b, uint(min), '0')
  486. case stdSecond:
  487. b = appendUint(b, uint(sec), 0)
  488. case stdZeroSecond:
  489. b = appendUint(b, uint(sec), '0')
  490. case stdPM:
  491. if hour >= 12 {
  492. b = append(b, "PM"...)
  493. } else {
  494. b = append(b, "AM"...)
  495. }
  496. case stdpm:
  497. if hour >= 12 {
  498. b = append(b, "pm"...)
  499. } else {
  500. b = append(b, "am"...)
  501. }
  502. case stdISO8601TZ, stdISO8601ColonTZ, stdISO8601SecondsTZ, stdISO8601ColonSecondsTZ, stdNumTZ, stdNumColonTZ, stdNumSecondsTz, stdNumColonSecondsTZ:
  503. // Ugly special case. We cheat and take the "Z" variants
  504. // to mean "the time zone as formatted for ISO 8601".
  505. if offset == 0 && (std == stdISO8601TZ || std == stdISO8601ColonTZ || std == stdISO8601SecondsTZ || std == stdISO8601ColonSecondsTZ) {
  506. b = append(b, 'Z')
  507. break
  508. }
  509. zone := offset / 60 // convert to minutes
  510. absoffset := offset
  511. if zone < 0 {
  512. b = append(b, '-')
  513. zone = -zone
  514. absoffset = -absoffset
  515. } else {
  516. b = append(b, '+')
  517. }
  518. b = appendUint(b, uint(zone/60), '0')
  519. if std == stdISO8601ColonTZ || std == stdNumColonTZ || std == stdISO8601ColonSecondsTZ || std == stdNumColonSecondsTZ {
  520. b = append(b, ':')
  521. }
  522. b = appendUint(b, uint(zone%60), '0')
  523. // append seconds if appropriate
  524. if std == stdISO8601SecondsTZ || std == stdNumSecondsTz || std == stdNumColonSecondsTZ || std == stdISO8601ColonSecondsTZ {
  525. if std == stdNumColonSecondsTZ || std == stdISO8601ColonSecondsTZ {
  526. b = append(b, ':')
  527. }
  528. b = appendUint(b, uint(absoffset%60), '0')
  529. }
  530. case stdTZ:
  531. if name != "" {
  532. b = append(b, name...)
  533. break
  534. }
  535. // No time zone known for this time, but we must print one.
  536. // Use the -0700 format.
  537. zone := offset / 60 // convert to minutes
  538. if zone < 0 {
  539. b = append(b, '-')
  540. zone = -zone
  541. } else {
  542. b = append(b, '+')
  543. }
  544. b = appendUint(b, uint(zone/60), '0')
  545. b = appendUint(b, uint(zone%60), '0')
  546. case stdFracSecond0, stdFracSecond9:
  547. b = formatNano(b, uint(t.Nanosecond()), std>>stdArgShift, std&stdMask == stdFracSecond9)
  548. }
  549. }
  550. return string(b)
  551. }
  552. var errBad = errors.New("bad value for field") // placeholder not passed to user
  553. // ParseError describes a problem parsing a time string.
  554. type ParseError struct {
  555. Layout string
  556. Value string
  557. LayoutElem string
  558. ValueElem string
  559. Message string
  560. }
  561. func quote(s string) string {
  562. return "\"" + s + "\""
  563. }
  564. // Error returns the string representation of a ParseError.
  565. func (e *ParseError) Error() string {
  566. if e.Message == "" {
  567. return "parsing time " +
  568. quote(e.Value) + " as " +
  569. quote(e.Layout) + ": cannot parse " +
  570. quote(e.ValueElem) + " as " +
  571. quote(e.LayoutElem)
  572. }
  573. return "parsing time " +
  574. quote(e.Value) + e.Message
  575. }
  576. // isDigit returns true if s[i] is a decimal digit, false if not or
  577. // if s[i] is out of range.
  578. func isDigit(s string, i int) bool {
  579. if len(s) <= i {
  580. return false
  581. }
  582. c := s[i]
  583. return '0' <= c && c <= '9'
  584. }
  585. // getnum parses s[0:1] or s[0:2] (fixed forces the latter)
  586. // as a decimal integer and returns the integer and the
  587. // remainder of the string.
  588. func getnum(s string, fixed bool) (int, string, error) {
  589. if !isDigit(s, 0) {
  590. return 0, s, errBad
  591. }
  592. if !isDigit(s, 1) {
  593. if fixed {
  594. return 0, s, errBad
  595. }
  596. return int(s[0] - '0'), s[1:], nil
  597. }
  598. return int(s[0]-'0')*10 + int(s[1]-'0'), s[2:], nil
  599. }
  600. func cutspace(s string) string {
  601. for len(s) > 0 && s[0] == ' ' {
  602. s = s[1:]
  603. }
  604. return s
  605. }
  606. // skip removes the given prefix from value,
  607. // treating runs of space characters as equivalent.
  608. func skip(value, prefix string) (string, error) {
  609. for len(prefix) > 0 {
  610. if prefix[0] == ' ' {
  611. if len(value) > 0 && value[0] != ' ' {
  612. return value, errBad
  613. }
  614. prefix = cutspace(prefix)
  615. value = cutspace(value)
  616. continue
  617. }
  618. if len(value) == 0 || value[0] != prefix[0] {
  619. return value, errBad
  620. }
  621. prefix = prefix[1:]
  622. value = value[1:]
  623. }
  624. return value, nil
  625. }
  626. // Parse parses a formatted string and returns the time value it represents.
  627. // The layout defines the format by showing how the reference time,
  628. // defined to be
  629. // Mon Jan 2 15:04:05 -0700 MST 2006
  630. // would be interpreted if it were the value; it serves as an example of
  631. // the input format. The same interpretation will then be made to the
  632. // input string.
  633. // Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard
  634. // and convenient representations of the reference time. For more information
  635. // about the formats and the definition of the reference time, see the
  636. // documentation for ANSIC and the other constants defined by this package.
  637. //
  638. // Elements omitted from the value are assumed to be zero or, when
  639. // zero is impossible, one, so parsing "3:04pm" returns the time
  640. // corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is
  641. // 0, this time is before the zero Time).
  642. // Years must be in the range 0000..9999. The day of the week is checked
  643. // for syntax but it is otherwise ignored.
  644. //
  645. // In the absence of a time zone indicator, Parse returns a time in UTC.
  646. //
  647. // When parsing a time with a zone offset like -0700, if the offset corresponds
  648. // to a time zone used by the current location (Local), then Parse uses that
  649. // location and zone in the returned time. Otherwise it records the time as
  650. // being in a fabricated location with time fixed at the given zone offset.
  651. //
  652. // When parsing a time with a zone abbreviation like MST, if the zone abbreviation
  653. // has a defined offset in the current location, then that offset is used.
  654. // The zone abbreviation "UTC" is recognized as UTC regardless of location.
  655. // If the zone abbreviation is unknown, Parse records the time as being
  656. // in a fabricated location with the given zone abbreviation and a zero offset.
  657. // This choice means that such a time can be parsed and reformatted with the
  658. // same layout losslessly, but the exact instant used in the representation will
  659. // differ by the actual zone offset. To avoid such problems, prefer time layouts
  660. // that use a numeric zone offset, or use ParseInLocation.
  661. func Parse(layout, value string) (Time, error) {
  662. return parse(layout, value, UTC, Local)
  663. }
  664. // ParseInLocation is like Parse but differs in two important ways.
  665. // First, in the absence of time zone information, Parse interprets a time as UTC;
  666. // ParseInLocation interprets the time as in the given location.
  667. // Second, when given a zone offset or abbreviation, Parse tries to match it
  668. // against the Local location; ParseInLocation uses the given location.
  669. func ParseInLocation(layout, value string, loc *Location) (Time, error) {
  670. return parse(layout, value, loc, loc)
  671. }
  672. func parse(layout, value string, defaultLocation, local *Location) (Time, error) {
  673. alayout, avalue := layout, value
  674. rangeErrString := "" // set if a value is out of range
  675. amSet := false // do we need to subtract 12 from the hour for midnight?
  676. pmSet := false // do we need to add 12 to the hour?
  677. // Time being constructed.
  678. var (
  679. year int
  680. month int = 1 // January
  681. day int = 1
  682. hour int
  683. min int
  684. sec int
  685. nsec int
  686. z *Location
  687. zoneOffset int = -1
  688. zoneName string
  689. )
  690. // Each iteration processes one std value.
  691. for {
  692. var err error
  693. prefix, std, suffix := nextStdChunk(layout)
  694. stdstr := layout[len(prefix) : len(layout)-len(suffix)]
  695. value, err = skip(value, prefix)
  696. if err != nil {
  697. return Time{}, &ParseError{alayout, avalue, prefix, value, ""}
  698. }
  699. if std == 0 {
  700. if len(value) != 0 {
  701. return Time{}, &ParseError{alayout, avalue, "", value, ": extra text: " + value}
  702. }
  703. break
  704. }
  705. layout = suffix
  706. var p string
  707. switch std & stdMask {
  708. case stdYear:
  709. if len(value) < 2 {
  710. err = errBad
  711. break
  712. }
  713. p, value = value[0:2], value[2:]
  714. year, err = atoi(p)
  715. if year >= 69 { // Unix time starts Dec 31 1969 in some time zones
  716. year += 1900
  717. } else {
  718. year += 2000
  719. }
  720. case stdLongYear:
  721. if len(value) < 4 || !isDigit(value, 0) {
  722. err = errBad
  723. break
  724. }
  725. p, value = value[0:4], value[4:]
  726. year, err = atoi(p)
  727. case stdMonth:
  728. month, value, err = lookup(shortMonthNames, value)
  729. case stdLongMonth:
  730. month, value, err = lookup(longMonthNames, value)
  731. case stdNumMonth, stdZeroMonth:
  732. month, value, err = getnum(value, std == stdZeroMonth)
  733. if month <= 0 || 12 < month {
  734. rangeErrString = "month"
  735. }
  736. case stdWeekDay:
  737. // Ignore weekday except for error checking.
  738. _, value, err = lookup(shortDayNames, value)
  739. case stdLongWeekDay:
  740. _, value, err = lookup(longDayNames, value)
  741. case stdDay, stdUnderDay, stdZeroDay:
  742. if std == stdUnderDay && len(value) > 0 && value[0] == ' ' {
  743. value = value[1:]
  744. }
  745. day, value, err = getnum(value, std == stdZeroDay)
  746. if day < 0 || 31 < day {
  747. rangeErrString = "day"
  748. }
  749. case stdHour:
  750. hour, value, err = getnum(value, false)
  751. if hour < 0 || 24 <= hour {
  752. rangeErrString = "hour"
  753. }
  754. case stdHour12, stdZeroHour12:
  755. hour, value, err = getnum(value, std == stdZeroHour12)
  756. if hour < 0 || 12 < hour {
  757. rangeErrString = "hour"
  758. }
  759. case stdMinute, stdZeroMinute:
  760. min, value, err = getnum(value, std == stdZeroMinute)
  761. if min < 0 || 60 <= min {
  762. rangeErrString = "minute"
  763. }
  764. case stdSecond, stdZeroSecond:
  765. sec, value, err = getnum(value, std == stdZeroSecond)
  766. if sec < 0 || 60 <= sec {
  767. rangeErrString = "second"
  768. }
  769. // Special case: do we have a fractional second but no
  770. // fractional second in the format?
  771. if len(value) >= 2 && value[0] == '.' && isDigit(value, 1) {
  772. _, std, _ = nextStdChunk(layout)
  773. std &= stdMask
  774. if std == stdFracSecond0 || std == stdFracSecond9 {
  775. // Fractional second in the layout; proceed normally
  776. break
  777. }
  778. // No fractional second in the layout but we have one in the input.
  779. n := 2
  780. for ; n < len(value) && isDigit(value, n); n++ {
  781. }
  782. nsec, rangeErrString, err = parseNanoseconds(value, n)
  783. value = value[n:]
  784. }
  785. case stdPM:
  786. if len(value) < 2 {
  787. err = errBad
  788. break
  789. }
  790. p, value = value[0:2], value[2:]
  791. switch p {
  792. case "PM":
  793. pmSet = true
  794. case "AM":
  795. amSet = true
  796. default:
  797. err = errBad
  798. }
  799. case stdpm:
  800. if len(value) < 2 {
  801. err = errBad
  802. break
  803. }
  804. p, value = value[0:2], value[2:]
  805. switch p {
  806. case "pm":
  807. pmSet = true
  808. case "am":
  809. amSet = true
  810. default:
  811. err = errBad
  812. }
  813. case stdISO8601TZ, stdISO8601ColonTZ, stdISO8601SecondsTZ, stdISO8601ColonSecondsTZ, stdNumTZ, stdNumShortTZ, stdNumColonTZ, stdNumSecondsTz, stdNumColonSecondsTZ:
  814. if (std == stdISO8601TZ || std == stdISO8601ColonTZ) && len(value) >= 1 && value[0] == 'Z' {
  815. value = value[1:]
  816. z = UTC
  817. break
  818. }
  819. var sign, hour, min, seconds string
  820. if std == stdISO8601ColonTZ || std == stdNumColonTZ {
  821. if len(value) < 6 {
  822. err = errBad
  823. break
  824. }
  825. if value[3] != ':' {
  826. err = errBad
  827. break
  828. }
  829. sign, hour, min, seconds, value = value[0:1], value[1:3], value[4:6], "00", value[6:]
  830. } else if std == stdNumShortTZ {
  831. if len(value) < 3 {
  832. err = errBad
  833. break
  834. }
  835. sign, hour, min, seconds, value = value[0:1], value[1:3], "00", "00", value[3:]
  836. } else if std == stdISO8601ColonSecondsTZ || std == stdNumColonSecondsTZ {
  837. if len(value) < 9 {
  838. err = errBad
  839. break
  840. }
  841. if value[3] != ':' || value[6] != ':' {
  842. err = errBad
  843. break
  844. }
  845. sign, hour, min, seconds, value = value[0:1], value[1:3], value[4:6], value[7:9], value[9:]
  846. } else if std == stdISO8601SecondsTZ || std == stdNumSecondsTz {
  847. if len(value) < 7 {
  848. err = errBad
  849. break
  850. }
  851. sign, hour, min, seconds, value = value[0:1], value[1:3], value[3:5], value[5:7], value[7:]
  852. } else {
  853. if len(value) < 5 {
  854. err = errBad
  855. break
  856. }
  857. sign, hour, min, seconds, value = value[0:1], value[1:3], value[3:5], "00", value[5:]
  858. }
  859. var hr, mm, ss int
  860. hr, err = atoi(hour)
  861. if err == nil {
  862. mm, err = atoi(min)
  863. }
  864. if err == nil {
  865. ss, err = atoi(seconds)
  866. }
  867. zoneOffset = (hr*60+mm)*60 + ss // offset is in seconds
  868. switch sign[0] {
  869. case '+':
  870. case '-':
  871. zoneOffset = -zoneOffset
  872. default:
  873. err = errBad
  874. }
  875. case stdTZ:
  876. // Does it look like a time zone?
  877. if len(value) >= 3 && value[0:3] == "UTC" {
  878. z = UTC
  879. value = value[3:]
  880. break
  881. }
  882. n, ok := parseTimeZone(value)
  883. if !ok {
  884. err = errBad
  885. break
  886. }
  887. zoneName, value = value[:n], value[n:]
  888. case stdFracSecond0:
  889. // stdFracSecond0 requires the exact number of digits as specified in
  890. // the layout.
  891. ndigit := 1 + (std >> stdArgShift)
  892. if len(value) < ndigit {
  893. err = errBad
  894. break
  895. }
  896. nsec, rangeErrString, err = parseNanoseconds(value, ndigit)
  897. value = value[ndigit:]
  898. case stdFracSecond9:
  899. if len(value) < 2 || value[0] != '.' || value[1] < '0' || '9' < value[1] {
  900. // Fractional second omitted.
  901. break
  902. }
  903. // Take any number of digits, even more than asked for,
  904. // because it is what the stdSecond case would do.
  905. i := 0
  906. for i < 9 && i+1 < len(value) && '0' <= value[i+1] && value[i+1] <= '9' {
  907. i++
  908. }
  909. nsec, rangeErrString, err = parseNanoseconds(value, 1+i)
  910. value = value[1+i:]
  911. }
  912. if rangeErrString != "" {
  913. return Time{}, &ParseError{alayout, avalue, stdstr, value, ": " + rangeErrString + " out of range"}
  914. }
  915. if err != nil {
  916. return Time{}, &ParseError{alayout, avalue, stdstr, value, ""}
  917. }
  918. }
  919. if pmSet && hour < 12 {
  920. hour += 12
  921. } else if amSet && hour == 12 {
  922. hour = 0
  923. }
  924. if z != nil {
  925. return Date(year, Month(month), day, hour, min, sec, nsec, z), nil
  926. }
  927. if zoneOffset != -1 {
  928. t := Date(year, Month(month), day, hour, min, sec, nsec, UTC)
  929. t.sec -= int64(zoneOffset)
  930. // Look for local zone with the given offset.
  931. // If that zone was in effect at the given time, use it.
  932. name, offset, _, _, _ := local.lookup(t.sec + internalToUnix)
  933. if offset == zoneOffset && (zoneName == "" || name == zoneName) {
  934. t.loc = local
  935. return t, nil
  936. }
  937. // Otherwise create fake zone to record offset.
  938. t.loc = FixedZone(zoneName, zoneOffset)
  939. return t, nil
  940. }
  941. if zoneName != "" {
  942. t := Date(year, Month(month), day, hour, min, sec, nsec, UTC)
  943. // Look for local zone with the given offset.
  944. // If that zone was in effect at the given time, use it.
  945. offset, _, ok := local.lookupName(zoneName, t.sec+internalToUnix)
  946. if ok {
  947. t.sec -= int64(offset)
  948. t.loc = local
  949. return t, nil
  950. }
  951. // Otherwise, create fake zone with unknown offset.
  952. if len(zoneName) > 3 && zoneName[:3] == "GMT" {
  953. offset, _ = atoi(zoneName[3:]) // Guaranteed OK by parseGMT.
  954. offset *= 3600
  955. }
  956. t.loc = FixedZone(zoneName, offset)
  957. return t, nil
  958. }
  959. // Otherwise, fall back to default.
  960. return Date(year, Month(month), day, hour, min, sec, nsec, defaultLocation), nil
  961. }
  962. // parseTimeZone parses a time zone string and returns its length. Time zones
  963. // are human-generated and unpredictable. We can't do precise error checking.
  964. // On the other hand, for a correct parse there must be a time zone at the
  965. // beginning of the string, so it's almost always true that there's one
  966. // there. We look at the beginning of the string for a run of upper-case letters.
  967. // If there are more than 5, it's an error.
  968. // If there are 4 or 5 and the last is a T, it's a time zone.
  969. // If there are 3, it's a time zone.
  970. // Otherwise, other than special cases, it's not a time zone.
  971. // GMT is special because it can have an hour offset.
  972. func parseTimeZone(value string) (length int, ok bool) {
  973. if len(value) < 3 {
  974. return 0, false
  975. }
  976. // Special case 1: ChST and MeST are the only zones with a lower-case letter.
  977. if len(value) >= 4 && (value[:4] == "ChST" || value[:4] == "MeST") {
  978. return 4, true
  979. }
  980. // Special case 2: GMT may have an hour offset; treat it specially.
  981. if value[:3] == "GMT" {
  982. length = parseGMT(value)
  983. return length, true
  984. }
  985. // How many upper-case letters are there? Need at least three, at most five.
  986. var nUpper int
  987. for nUpper = 0; nUpper < 6; nUpper++ {
  988. if nUpper >= len(value) {
  989. break
  990. }
  991. if c := value[nUpper]; c < 'A' || 'Z' < c {
  992. break
  993. }
  994. }
  995. switch nUpper {
  996. case 0, 1, 2, 6:
  997. return 0, false
  998. case 5: // Must end in T to match.
  999. if value[4] == 'T' {
  1000. return 5, true
  1001. }
  1002. case 4: // Must end in T to match.
  1003. if value[3] == 'T' {
  1004. return 4, true
  1005. }
  1006. case 3:
  1007. return 3, true
  1008. }
  1009. return 0, false
  1010. }
  1011. // parseGMT parses a GMT time zone. The input string is known to start "GMT".
  1012. // The function checks whether that is followed by a sign and a number in the
  1013. // range -14 through 12 excluding zero.
  1014. func parseGMT(value string) int {
  1015. value = value[3:]
  1016. if len(value) == 0 {
  1017. return 3
  1018. }
  1019. sign := value[0]
  1020. if sign != '-' && sign != '+' {
  1021. return 3
  1022. }
  1023. x, rem, err := leadingInt(value[1:])
  1024. if err != nil {
  1025. return 3
  1026. }
  1027. if sign == '-' {
  1028. x = -x
  1029. }
  1030. if x == 0 || x < -14 || 12 < x {
  1031. return 3
  1032. }
  1033. return 3 + len(value) - len(rem)
  1034. }
  1035. func parseNanoseconds(value string, nbytes int) (ns int, rangeErrString string, err error) {
  1036. if value[0] != '.' {
  1037. err = errBad
  1038. return
  1039. }
  1040. if ns, err = atoi(value[1:nbytes]); err != nil {
  1041. return
  1042. }
  1043. if ns < 0 || 1e9 <= ns {
  1044. rangeErrString = "fractional second"
  1045. return
  1046. }
  1047. // We need nanoseconds, which means scaling by the number
  1048. // of missing digits in the format, maximum length 10. If it's
  1049. // longer than 10, we won't scale.
  1050. scaleDigits := 10 - nbytes
  1051. for i := 0; i < scaleDigits; i++ {
  1052. ns *= 10
  1053. }
  1054. return
  1055. }
  1056. var errLeadingInt = errors.New("time: bad [0-9]*") // never printed
  1057. // leadingInt consumes the leading [0-9]* from s.
  1058. func leadingInt(s string) (x int64, rem string, err error) {
  1059. i := 0
  1060. for ; i < len(s); i++ {
  1061. c := s[i]
  1062. if c < '0' || c > '9' {
  1063. break
  1064. }
  1065. if x >= (1<<63-10)/10 {
  1066. // overflow
  1067. return 0, "", errLeadingInt
  1068. }
  1069. x = x*10 + int64(c) - '0'
  1070. }
  1071. return x, s[i:], nil
  1072. }
  1073. var unitMap = map[string]float64{
  1074. "ns": float64(Nanosecond),
  1075. "us": float64(Microsecond),
  1076. "µs": float64(Microsecond), // U+00B5 = micro symbol
  1077. "μs": float64(Microsecond), // U+03BC = Greek letter mu
  1078. "ms": float64(Millisecond),
  1079. "s": float64(Second),
  1080. "m": float64(Minute),
  1081. "h": float64(Hour),
  1082. }
  1083. // ParseDuration parses a duration string.
  1084. // A duration string is a possibly signed sequence of
  1085. // decimal numbers, each with optional fraction and a unit suffix,
  1086. // such as "300ms", "-1.5h" or "2h45m".
  1087. // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
  1088. func ParseDuration(s string) (Duration, error) {
  1089. // [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+
  1090. orig := s
  1091. f := float64(0)
  1092. neg := false
  1093. // Consume [-+]?
  1094. if s != "" {
  1095. c := s[0]
  1096. if c == '-' || c == '+' {
  1097. neg = c == '-'
  1098. s = s[1:]
  1099. }
  1100. }
  1101. // Special case: if all that is left is "0", this is zero.
  1102. if s == "0" {
  1103. return 0, nil
  1104. }
  1105. if s == "" {
  1106. return 0, errors.New("time: invalid duration " + orig)
  1107. }
  1108. for s != "" {
  1109. g := float64(0) // this element of the sequence
  1110. var x int64
  1111. var err error
  1112. // The next character must be [0-9.]
  1113. if !(s[0] == '.' || ('0' <= s[0] && s[0] <= '9')) {
  1114. return 0, errors.New("time: invalid duration " + orig)
  1115. }
  1116. // Consume [0-9]*
  1117. pl := len(s)
  1118. x, s, err = leadingInt(s)
  1119. if err != nil {
  1120. return 0, errors.New("time: invalid duration " + orig)
  1121. }
  1122. g = float64(x)
  1123. pre := pl != len(s) // whether we consumed anything before a period
  1124. // Consume (\.[0-9]*)?
  1125. post := false
  1126. if s != "" && s[0] == '.' {
  1127. s = s[1:]
  1128. pl := len(s)
  1129. x, s, err = leadingInt(s)
  1130. if err != nil {
  1131. return 0, errors.New("time: invalid duration " + orig)
  1132. }
  1133. scale := 1.0
  1134. for n := pl - len(s); n > 0; n-- {
  1135. scale *= 10
  1136. }
  1137. g += float64(x) / scale
  1138. post = pl != len(s)
  1139. }
  1140. if !pre && !post {
  1141. // no digits (e.g. ".s" or "-.s")
  1142. return 0, errors.New("time: invalid duration " + orig)
  1143. }
  1144. // Consume unit.
  1145. i := 0
  1146. for ; i < len(s); i++ {
  1147. c := s[i]
  1148. if c == '.' || ('0' <= c && c <= '9') {
  1149. break
  1150. }
  1151. }
  1152. if i == 0 {
  1153. return 0, errors.New("time: missing unit in duration " + orig)
  1154. }
  1155. u := s[:i]
  1156. s = s[i:]
  1157. unit, ok := unitMap[u]
  1158. if !ok {
  1159. return 0, errors.New("time: unknown unit " + u + " in duration " + orig)
  1160. }
  1161. f += g * unit
  1162. }
  1163. if neg {
  1164. f = -f
  1165. }
  1166. if f < float64(-1<<63) || f > float64(1<<63-1) {
  1167. return 0, errors.New("time: overflow parsing duration")
  1168. }
  1169. return Duration(f), nil
  1170. }