format.go 29.8 KB
Newer Older
1 2 3 4
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6
package time

7
import "errors"
8

9 10
// These are predefined layouts for use in Time.Format and Time.Parse.
// The reference time used in the layouts is:
11
//	Mon Jan 2 15:04:05 MST 2006
12
// which is Unix time 1136239445. Since MST is GMT-0700,
13
// the reference time can be thought of as
14
//	01/02 03:04:05PM '06 -0700
15
// To define your own format, write down what the reference time would look
16
// like formatted your way; see the values of constants like ANSIC,
17 18 19
// StampMicro or Kitchen for examples. The model is to demonstrate what the
// reference time looks like so that the Format and Parse methods can apply
// the same transformation to a general time value.
20 21 22 23
//
// Within the format string, an underscore _ represents a space that may be
// replaced by a digit if the following number (a day) has two digits; for
// compatibility with fixed-width Unix time formats.
24
//
25
// A decimal point followed by one or more zeros represents a fractional
26 27 28 29
// second, printed to the given number of decimal places.  A decimal point
// followed by one or more nines represents a fractional second, printed to
// the given number of decimal places, with trailing zeros removed.
// When parsing (only), the input may contain a fractional second
30 31 32
// field immediately after the seconds field, even if the layout does not
// signify its presence. In that case a decimal point followed by a maximal
// series of digits is parsed as a fractional second.
33
//
34 35 36 37 38 39 40 41
// Numeric time zone offsets format as follows:
//	-0700  ±hhmm
//	-07:00 ±hh:mm
// Replacing the sign in the format with a Z triggers
// the ISO 8601 behavior of printing Z instead of an
// offset for the UTC zone.  Thus:
//	Z0700  Z or ±hhmm
//	Z07:00 Z or ±hh:mm
42
const (
43 44 45
	ANSIC       = "Mon Jan _2 15:04:05 2006"
	UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
	RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
46 47
	RFC822      = "02 Jan 06 15:04 MST"
	RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
48 49 50 51 52 53
	RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
	RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
	RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
	RFC3339     = "2006-01-02T15:04:05Z07:00"
	RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
	Kitchen     = "3:04PM"
54 55 56 57 58
	// Handy time stamps.
	Stamp      = "Jan _2 15:04:05"
	StampMilli = "Jan _2 15:04:05.000"
	StampMicro = "Jan _2 15:04:05.000000"
	StampNano  = "Jan _2 15:04:05.000000000"
59 60 61
)

const (
Russ Cox's avatar
Russ Cox committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
	_                 = iota
	stdLongMonth      = iota + stdNeedDate  // "January"
	stdMonth                                // "Jan"
	stdNumMonth                             // "1"
	stdZeroMonth                            // "01"
	stdLongWeekDay                          // "Monday"
	stdWeekDay                              // "Mon"
	stdDay                                  // "2"
	stdUnderDay                             // "_2"
	stdZeroDay                              // "02"
	stdHour           = iota + stdNeedClock // "15"
	stdHour12                               // "3"
	stdZeroHour12                           // "03"
	stdMinute                               // "4"
	stdZeroMinute                           // "04"
	stdSecond                               // "5"
	stdZeroSecond                           // "05"
	stdLongYear       = iota + stdNeedDate  // "2006"
	stdYear                                 // "06"
	stdPM             = iota + stdNeedClock // "PM"
	stdpm                                   // "pm"
	stdTZ             = iota                // "MST"
	stdISO8601TZ                            // "Z0700"  // prints Z for UTC
	stdISO8601ColonTZ                       // "Z07:00" // prints Z for UTC
	stdNumTZ                                // "-0700"  // always numeric
	stdNumShortTZ                           // "-07"    // always numeric
	stdNumColonTZ                           // "-07:00" // always numeric
	stdFracSecond0                          // ".0", ".00", ... , trailing zeros included
	stdFracSecond9                          // ".9", ".99", ..., trailing zeros omitted

	stdNeedDate  = 1 << 8             // need month, day, year
	stdNeedClock = 2 << 8             // need hour, minute, second
	stdArgShift  = 16                 // extra argument in high bits, above low stdArgShift
	stdMask      = 1<<stdArgShift - 1 // mask out argument
96 97
)

Russ Cox's avatar
Russ Cox committed
98 99 100
// std0x records the std values for "01", "02", ..., "06".
var std0x = [...]int{stdZeroMonth, stdZeroDay, stdZeroHour12, stdZeroMinute, stdZeroSecond, stdYear}

101 102
// nextStdChunk finds the first occurrence of a std string in
// layout and returns the text before, the std string, and the text after.
Russ Cox's avatar
Russ Cox committed
103
func nextStdChunk(layout string) (prefix string, std int, suffix string) {
104
	for i := 0; i < len(layout); i++ {
Russ Cox's avatar
Russ Cox committed
105
		switch c := int(layout[i]); c {
106
		case 'J': // January, Jan
Russ Cox's avatar
Russ Cox committed
107 108 109 110
			if len(layout) >= i+3 && layout[i:i+3] == "Jan" {
				if len(layout) >= i+7 && layout[i:i+7] == "January" {
					return layout[0:i], stdLongMonth, layout[i+7:]
				}
111 112 113 114 115
				return layout[0:i], stdMonth, layout[i+3:]
			}

		case 'M': // Monday, Mon, MST
			if len(layout) >= i+3 {
Russ Cox's avatar
Russ Cox committed
116 117 118 119
				if layout[i:i+3] == "Mon" {
					if len(layout) >= i+6 && layout[i:i+6] == "Monday" {
						return layout[0:i], stdLongWeekDay, layout[i+6:]
					}
120 121
					return layout[0:i], stdWeekDay, layout[i+3:]
				}
Russ Cox's avatar
Russ Cox committed
122
				if layout[i:i+3] == "MST" {
123 124 125 126 127 128
					return layout[0:i], stdTZ, layout[i+3:]
				}
			}

		case '0': // 01, 02, 03, 04, 05, 06
			if len(layout) >= i+2 && '1' <= layout[i+1] && layout[i+1] <= '6' {
Russ Cox's avatar
Russ Cox committed
129
				return layout[0:i], std0x[layout[i+1]-'1'], layout[i+2:]
130 131 132 133 134 135 136 137 138
			}

		case '1': // 15, 1
			if len(layout) >= i+2 && layout[i+1] == '5' {
				return layout[0:i], stdHour, layout[i+2:]
			}
			return layout[0:i], stdNumMonth, layout[i+1:]

		case '2': // 2006, 2
Russ Cox's avatar
Russ Cox committed
139
			if len(layout) >= i+4 && layout[i:i+4] == "2006" {
140 141 142 143 144 145 146 147 148
				return layout[0:i], stdLongYear, layout[i+4:]
			}
			return layout[0:i], stdDay, layout[i+1:]

		case '_': // _2
			if len(layout) >= i+2 && layout[i+1] == '2' {
				return layout[0:i], stdUnderDay, layout[i+2:]
			}

Russ Cox's avatar
Russ Cox committed
149 150 151 152 153 154 155 156
		case '3':
			return layout[0:i], stdHour12, layout[i+1:]

		case '4':
			return layout[0:i], stdMinute, layout[i+1:]

		case '5':
			return layout[0:i], stdSecond, layout[i+1:]
157 158 159

		case 'P': // PM
			if len(layout) >= i+2 && layout[i+1] == 'M' {
Russ Cox's avatar
Russ Cox committed
160
				return layout[0:i], stdPM, layout[i+2:]
161 162 163 164
			}

		case 'p': // pm
			if len(layout) >= i+2 && layout[i+1] == 'm' {
Russ Cox's avatar
Russ Cox committed
165
				return layout[0:i], stdpm, layout[i+2:]
166 167
			}

168
		case '-': // -0700, -07:00, -07
Russ Cox's avatar
Russ Cox committed
169 170
			if len(layout) >= i+5 && layout[i:i+5] == "-0700" {
				return layout[0:i], stdNumTZ, layout[i+5:]
171
			}
Russ Cox's avatar
Russ Cox committed
172 173
			if len(layout) >= i+6 && layout[i:i+6] == "-07:00" {
				return layout[0:i], stdNumColonTZ, layout[i+6:]
174
			}
Russ Cox's avatar
Russ Cox committed
175 176
			if len(layout) >= i+3 && layout[i:i+3] == "-07" {
				return layout[0:i], stdNumShortTZ, layout[i+3:]
177
			}
178
		case 'Z': // Z0700, Z07:00
Russ Cox's avatar
Russ Cox committed
179 180
			if len(layout) >= i+5 && layout[i:i+5] == "Z0700" {
				return layout[0:i], stdISO8601TZ, layout[i+5:]
181
			}
Russ Cox's avatar
Russ Cox committed
182 183
			if len(layout) >= i+6 && layout[i:i+6] == "Z07:00" {
				return layout[0:i], stdISO8601ColonTZ, layout[i+6:]
184
			}
185 186 187 188 189 190 191 192 193
		case '.': // .000 or .999 - repeated digits for fractional seconds.
			if i+1 < len(layout) && (layout[i+1] == '0' || layout[i+1] == '9') {
				ch := layout[i+1]
				j := i + 1
				for j < len(layout) && layout[j] == ch {
					j++
				}
				// String of digits must end here - only fractional second is all digits.
				if !isDigit(layout, j) {
Russ Cox's avatar
Russ Cox committed
194 195 196 197 198 199
					std := stdFracSecond0
					if layout[i+1] == '9' {
						std = stdFracSecond9
					}
					std |= (j - (i + 1)) << stdArgShift
					return layout[0:i], std, layout[j:]
200
				}
201
			}
202 203
		}
	}
Russ Cox's avatar
Russ Cox committed
204
	return layout, 0, ""
205 206
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
var longDayNames = []string{
	"Sunday",
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Saturday",
}

var shortDayNames = []string{
	"Sun",
	"Mon",
	"Tue",
	"Wed",
	"Thu",
	"Fri",
	"Sat",
}

var shortMonthNames = []string{
	"---",
	"Jan",
	"Feb",
	"Mar",
	"Apr",
	"May",
	"Jun",
	"Jul",
	"Aug",
	"Sep",
	"Oct",
	"Nov",
	"Dec",
}

var longMonthNames = []string{
	"---",
	"January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December",
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
// match returns true if s1 and s2 match ignoring case.
// It is assumed s1 and s2 are the same length.
func match(s1, s2 string) bool {
	for i := 0; i < len(s1); i++ {
		c1 := s1[i]
		c2 := s2[i]
		if c1 != c2 {
			// Switch to lower-case; 'a'-'A' is known to be a single bit.
			c1 |= 'a' - 'A'
			c2 |= 'a' - 'A'
			if c1 != c2 || c1 < 'a' || c1 > 'z' {
				return false
			}
		}
	}
	return true
}

277
func lookup(tab []string, val string) (int, string, error) {
278
	for i, v := range tab {
279
		if len(val) >= len(v) && match(val[0:len(v)], v) {
280
			return i, val[len(v):], nil
281 282
		}
	}
283
	return -1, val, errBad
284 285
}

Russ Cox's avatar
Russ Cox committed
286 287 288
// appendUint appends the decimal form of x to b and returns the result.
// If x is a single-digit number and pad != 0, appendUint inserts the pad byte
// before the digit.
289
// Duplicates functionality in strconv, but avoids dependency.
Russ Cox's avatar
Russ Cox committed
290 291 292 293 294 295 296 297 298 299 300 301 302
func appendUint(b []byte, x uint, pad byte) []byte {
	if x < 10 {
		if pad != 0 {
			b = append(b, pad)
		}
		return append(b, byte('0'+x))
	}
	if x < 100 {
		b = append(b, byte('0'+x/10))
		b = append(b, byte('0'+x%10))
		return b
	}

303 304 305
	var buf [32]byte
	n := len(buf)
	if x == 0 {
Russ Cox's avatar
Russ Cox committed
306
		return append(b, '0')
307
	}
Russ Cox's avatar
Russ Cox committed
308
	for x >= 10 {
309
		n--
Russ Cox's avatar
Russ Cox committed
310 311
		buf[n] = byte(x%10 + '0')
		x /= 10
312
	}
Russ Cox's avatar
Russ Cox committed
313 314 315
	n--
	buf[n] = byte(x + '0')
	return append(b, buf[n:]...)
316 317 318 319 320 321 322
}

// Never printed, just needs to be non-nil for return by atoi.
var atoiError = errors.New("time: invalid number")

// Duplicates functionality in strconv, but avoids dependency.
func atoi(s string) (x int, err error) {
David Symonds's avatar
David Symonds committed
323 324 325 326
	neg := false
	if s != "" && s[0] == '-' {
		neg = true
		s = s[1:]
327
	}
328 329
	q, rem, err := leadingInt(s)
	x = int(q)
David Symonds's avatar
David Symonds committed
330
	if err != nil || rem != "" {
331 332
		return 0, atoiError
	}
David Symonds's avatar
David Symonds committed
333
	if neg {
334 335 336 337 338
		x = -x
	}
	return x, nil
}

Russ Cox's avatar
Russ Cox committed
339 340 341 342 343 344 345 346 347
// formatNano appends a fractional second, as nanoseconds, to b
// and returns the result.
func formatNano(b []byte, nanosec uint, n int, trim bool) []byte {
	u := nanosec
	var buf [9]byte
	for start := len(buf); start > 0; {
		start--
		buf[start] = byte(u%10 + '0')
		u /= 10
348
	}
349

350 351 352
	if n > 9 {
		n = 9
	}
353
	if trim {
Russ Cox's avatar
Russ Cox committed
354
		for n > 0 && buf[n-1] == '0' {
355 356 357
			n--
		}
		if n == 0 {
Russ Cox's avatar
Russ Cox committed
358
			return b
359 360
		}
	}
Russ Cox's avatar
Russ Cox committed
361 362
	b = append(b, '.')
	return append(b, buf[:n]...)
363 364
}

365
// String returns the time formatted using the format string
366
//	"2006-01-02 15:04:05.999999999 -0700 MST"
367
func (t Time) String() string {
368
	return t.Format("2006-01-02 15:04:05.999999999 -0700 MST")
369 370
}

371
// Format returns a textual representation of the time value formatted
372 373
// according to layout, which defines the format by showing how the reference
// time,
374
//	Mon Jan 2 15:04:05 -0700 MST 2006
375 376 377 378 379 380 381
// would be displayed if it were the value; it serves as an example of the
// desired output. The same display rules will then be aplied to the time
// value.
// Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard
// and convenient representations of the reference time. For more information
// about the formats and the definition of the reference time, see the
// documentation for ANSIC and the other constants defined by this package.
382 383
func (t Time) Format(layout string) string {
	var (
Russ Cox's avatar
Russ Cox committed
384 385
		name, offset, abs = t.locabs()

386 387 388 389 390 391
		year  int = -1
		month Month
		day   int
		hour  int = -1
		min   int
		sec   int
Russ Cox's avatar
Russ Cox committed
392 393 394

		b   []byte
		buf [64]byte
395
	)
Russ Cox's avatar
Russ Cox committed
396 397 398 399 400 401
	max := len(layout) + 10
	if max <= len(buf) {
		b = buf[:0]
	} else {
		b = make([]byte, 0, max)
	}
402
	// Each iteration generates one std value.
Russ Cox's avatar
Russ Cox committed
403
	for layout != "" {
404
		prefix, std, suffix := nextStdChunk(layout)
Russ Cox's avatar
Russ Cox committed
405 406 407 408
		if prefix != "" {
			b = append(b, prefix...)
		}
		if std == 0 {
409
			break
410
		}
Russ Cox's avatar
Russ Cox committed
411
		layout = suffix
412 413

		// Compute year, month, day if needed.
Russ Cox's avatar
Russ Cox committed
414 415
		if year < 0 && std&stdNeedDate != 0 {
			year, month, day, _ = absDate(abs, true)
416 417 418
		}

		// Compute hour, minute, second if needed.
Russ Cox's avatar
Russ Cox committed
419 420
		if hour < 0 && std&stdNeedClock != 0 {
			hour, min, sec = absClock(abs)
421 422
		}

Russ Cox's avatar
Russ Cox committed
423
		switch std & stdMask {
424
		case stdYear:
Russ Cox's avatar
Russ Cox committed
425 426 427 428 429
			y := year
			if y < 0 {
				y = -y
			}
			b = appendUint(b, uint(y%100), '0')
430
		case stdLongYear:
431
			// Pad year to at least 4 digits.
Russ Cox's avatar
Russ Cox committed
432
			y := year
433 434
			switch {
			case year <= -1000:
Russ Cox's avatar
Russ Cox committed
435 436
				b = append(b, '-')
				y = -y
437
			case year <= -100:
Russ Cox's avatar
Russ Cox committed
438 439
				b = append(b, "-0"...)
				y = -y
440
			case year <= -10:
Russ Cox's avatar
Russ Cox committed
441 442
				b = append(b, "-00"...)
				y = -y
443
			case year < 0:
Russ Cox's avatar
Russ Cox committed
444 445
				b = append(b, "-000"...)
				y = -y
446
			case year < 10:
Russ Cox's avatar
Russ Cox committed
447
				b = append(b, "000"...)
448
			case year < 100:
Russ Cox's avatar
Russ Cox committed
449
				b = append(b, "00"...)
450
			case year < 1000:
Russ Cox's avatar
Russ Cox committed
451
				b = append(b, '0')
452
			}
Russ Cox's avatar
Russ Cox committed
453
			b = appendUint(b, uint(y), 0)
454
		case stdMonth:
Russ Cox's avatar
Russ Cox committed
455
			b = append(b, month.String()[:3]...)
456
		case stdLongMonth:
Russ Cox's avatar
Russ Cox committed
457 458
			m := month.String()
			b = append(b, m...)
459
		case stdNumMonth:
Russ Cox's avatar
Russ Cox committed
460
			b = appendUint(b, uint(month), 0)
461
		case stdZeroMonth:
Russ Cox's avatar
Russ Cox committed
462
			b = appendUint(b, uint(month), '0')
463
		case stdWeekDay:
Russ Cox's avatar
Russ Cox committed
464
			b = append(b, absWeekday(abs).String()[:3]...)
465
		case stdLongWeekDay:
Russ Cox's avatar
Russ Cox committed
466 467
			s := absWeekday(abs).String()
			b = append(b, s...)
468
		case stdDay:
Russ Cox's avatar
Russ Cox committed
469
			b = appendUint(b, uint(day), 0)
470
		case stdUnderDay:
Russ Cox's avatar
Russ Cox committed
471
			b = appendUint(b, uint(day), ' ')
472
		case stdZeroDay:
Russ Cox's avatar
Russ Cox committed
473
			b = appendUint(b, uint(day), '0')
474
		case stdHour:
Russ Cox's avatar
Russ Cox committed
475
			b = appendUint(b, uint(hour), '0')
476
		case stdHour12:
Rob Pike's avatar
Rob Pike committed
477
			// Noon is 12PM, midnight is 12AM.
478
			hr := hour % 12
Rob Pike's avatar
Rob Pike committed
479 480
			if hr == 0 {
				hr = 12
481
			}
Russ Cox's avatar
Russ Cox committed
482
			b = appendUint(b, uint(hr), 0)
483
		case stdZeroHour12:
Rob Pike's avatar
Rob Pike committed
484
			// Noon is 12PM, midnight is 12AM.
485
			hr := hour % 12
Rob Pike's avatar
Rob Pike committed
486 487
			if hr == 0 {
				hr = 12
488
			}
Russ Cox's avatar
Russ Cox committed
489
			b = appendUint(b, uint(hr), '0')
490
		case stdMinute:
Russ Cox's avatar
Russ Cox committed
491
			b = appendUint(b, uint(min), 0)
492
		case stdZeroMinute:
Russ Cox's avatar
Russ Cox committed
493
			b = appendUint(b, uint(min), '0')
494
		case stdSecond:
Russ Cox's avatar
Russ Cox committed
495
			b = appendUint(b, uint(sec), 0)
496
		case stdZeroSecond:
Russ Cox's avatar
Russ Cox committed
497
			b = appendUint(b, uint(sec), '0')
498 499
		case stdPM:
			if hour >= 12 {
Russ Cox's avatar
Russ Cox committed
500
				b = append(b, "PM"...)
501
			} else {
Russ Cox's avatar
Russ Cox committed
502
				b = append(b, "AM"...)
503 504 505
			}
		case stdpm:
			if hour >= 12 {
Russ Cox's avatar
Russ Cox committed
506
				b = append(b, "pm"...)
507
			} else {
Russ Cox's avatar
Russ Cox committed
508
				b = append(b, "am"...)
509
			}
510 511 512
		case stdISO8601TZ, stdISO8601ColonTZ, stdNumTZ, stdNumColonTZ:
			// Ugly special case.  We cheat and take the "Z" variants
			// to mean "the time zone as formatted for ISO 8601".
Russ Cox's avatar
Russ Cox committed
513 514
			if offset == 0 && (std == stdISO8601TZ || std == stdISO8601ColonTZ) {
				b = append(b, 'Z')
515 516
				break
			}
517
			zone := offset / 60 // convert to minutes
518
			if zone < 0 {
Russ Cox's avatar
Russ Cox committed
519
				b = append(b, '-')
520
				zone = -zone
521
			} else {
Russ Cox's avatar
Russ Cox committed
522
				b = append(b, '+')
523
			}
Russ Cox's avatar
Russ Cox committed
524
			b = appendUint(b, uint(zone/60), '0')
525
			if std == stdISO8601ColonTZ || std == stdNumColonTZ {
Russ Cox's avatar
Russ Cox committed
526
				b = append(b, ':')
527
			}
Russ Cox's avatar
Russ Cox committed
528
			b = appendUint(b, uint(zone%60), '0')
529
		case stdTZ:
530
			if name != "" {
Russ Cox's avatar
Russ Cox committed
531 532
				b = append(b, name...)
				break
533
			}
Russ Cox's avatar
Russ Cox committed
534 535 536 537 538 539 540 541
			// No time zone known for this time, but we must print one.
			// Use the -0700 format.
			zone := offset / 60 // convert to minutes
			if zone < 0 {
				b = append(b, '-')
				zone = -zone
			} else {
				b = append(b, '+')
542
			}
Russ Cox's avatar
Russ Cox committed
543 544 545 546
			b = appendUint(b, uint(zone/60), '0')
			b = appendUint(b, uint(zone%60), '0')
		case stdFracSecond0, stdFracSecond9:
			b = formatNano(b, uint(t.Nanosecond()), std>>stdArgShift, std&stdMask == stdFracSecond9)
547 548
		}
	}
Russ Cox's avatar
Russ Cox committed
549
	return string(b)
550 551
}

552
var errBad = errors.New("bad value for field") // placeholder not passed to user
553 554 555 556 557 558 559 560 561 562

// ParseError describes a problem parsing a time string.
type ParseError struct {
	Layout     string
	Value      string
	LayoutElem string
	ValueElem  string
	Message    string
}

563 564 565 566
func quote(s string) string {
	return "\"" + s + "\""
}

567
// Error returns the string representation of a ParseError.
568
func (e *ParseError) Error() string {
569
	if e.Message == "" {
Russ Cox's avatar
Russ Cox committed
570
		return "parsing time " +
571 572 573 574
			quote(e.Value) + " as " +
			quote(e.Layout) + ": cannot parse " +
			quote(e.ValueElem) + " as " +
			quote(e.LayoutElem)
575 576
	}
	return "parsing time " +
577
		quote(e.Value) + e.Message
578 579
}

580 581 582 583 584 585 586 587 588 589
// isDigit returns true if s[i] is a decimal digit, false if not or
// if s[i] is out of range.
func isDigit(s string, i int) bool {
	if len(s) <= i {
		return false
	}
	c := s[i]
	return '0' <= c && c <= '9'
}

590 591 592
// getnum parses s[0:1] or s[0:2] (fixed forces the latter)
// as a decimal integer and returns the integer and the
// remainder of the string.
593
func getnum(s string, fixed bool) (int, string, error) {
594
	if !isDigit(s, 0) {
595
		return 0, s, errBad
596
	}
597
	if !isDigit(s, 1) {
598 599
		if fixed {
			return 0, s, errBad
600
		}
601
		return int(s[0] - '0'), s[1:], nil
602
	}
603
	return int(s[0]-'0')*10 + int(s[1]-'0'), s[2:], nil
604 605
}

606 607 608 609 610 611 612 613 614
func cutspace(s string) string {
	for len(s) > 0 && s[0] == ' ' {
		s = s[1:]
	}
	return s
}

// skip removes the given prefix from value,
// treating runs of space characters as equivalent.
615
func skip(value, prefix string) (string, error) {
616 617 618
	for len(prefix) > 0 {
		if prefix[0] == ' ' {
			if len(value) > 0 && value[0] != ' ' {
619
				return value, errBad
620 621 622 623 624 625
			}
			prefix = cutspace(prefix)
			value = cutspace(value)
			continue
		}
		if len(value) == 0 || value[0] != prefix[0] {
626
			return value, errBad
627 628 629 630 631 632
		}
		prefix = prefix[1:]
		value = value[1:]
	}
	return value, nil
}
633

634
// Parse parses a formatted string and returns the time value it represents.
635
// The layout  defines the format by showing how the reference time,
636
//	Mon Jan 2 15:04:05 -0700 MST 2006
Rob Pike's avatar
Rob Pike committed
637
// would be interpreted if it were the value; it serves as an example of
638 639 640 641 642 643
// the input format. The same interpretation will then be made to the
// input string.
// Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard
// and convenient representations of the reference time. For more information
// about the formats and the definition of the reference time, see the
// documentation for ANSIC and the other constants defined by this package.
644
//
645
// Elements omitted from the value are assumed to be zero or, when
646
// zero is impossible, one, so parsing "3:04pm" returns the time
647 648
// corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is
// 0, this time is before the zero Time).
Rob Pike's avatar
Rob Pike committed
649 650
// Years must be in the range 0000..9999. The day of the week is checked
// for syntax but it is otherwise ignored.
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
//
// In the absence of a time zone indicator, Parse returns a time in UTC.
//
// When parsing a time with a zone offset like -0700, if the offset corresponds
// to a time zone used by the current location (Local), then Parse uses that
// location and zone in the returned time. Otherwise it records the time as
// being in a fabricated location with time fixed at the given zone offset.
//
// When parsing a time with a zone abbreviation like MST, if the zone abbreviation
// has a defined offset in the current location, then that offset is used.
// The zone abbreviation "UTC" is recognized as UTC regardless of location.
// If the zone abbreviation is unknown, Parse records the time as being
// in a fabricated location with the given zone abbreviation and a zero offset.
// This choice means that such a time can be parse and reformatted with the
// same layout losslessly, but the exact instant used in the representation will
// differ by the actual zone offset. To avoid such problems, prefer time layouts
// that use a numeric zone offset, or use ParseInLocation.
668
func Parse(layout, value string) (Time, error) {
669 670 671 672 673 674 675 676 677 678 679 680 681
	return parse(layout, value, UTC, Local)
}

// ParseInLocation is like Parse but differs in two important ways.
// First, in the absence of time zone information, Parse interprets a time as UTC;
// ParseInLocation interprets the time as in the given location.
// Second, when given a zone offset or abbreviation, Parse tries to match it
// against the Local location; ParseInLocation uses the given location.
func ParseInLocation(layout, value string, loc *Location) (Time, error) {
	return parse(layout, value, loc, loc)
}

func parse(layout, value string, defaultLocation, local *Location) (Time, error) {
682
	alayout, avalue := layout, value
683
	rangeErrString := "" // set if a value is out of range
Rob Pike's avatar
Rob Pike committed
684
	amSet := false       // do we need to subtract 12 from the hour for midnight?
685
	pmSet := false       // do we need to add 12 to the hour?
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700

	// Time being constructed.
	var (
		year       int
		month      int = 1 // January
		day        int = 1
		hour       int
		min        int
		sec        int
		nsec       int
		z          *Location
		zoneOffset int = -1
		zoneName   string
	)

701 702
	// Each iteration processes one std value.
	for {
703
		var err error
704
		prefix, std, suffix := nextStdChunk(layout)
Russ Cox's avatar
Russ Cox committed
705
		stdstr := layout[len(prefix) : len(layout)-len(suffix)]
706 707
		value, err = skip(value, prefix)
		if err != nil {
708
			return Time{}, &ParseError{alayout, avalue, prefix, value, ""}
709
		}
Russ Cox's avatar
Russ Cox committed
710
		if std == 0 {
711
			if len(value) != 0 {
712
				return Time{}, &ParseError{alayout, avalue, "", value, ": extra text: " + value}
713
			}
714
			break
715
		}
716 717
		layout = suffix
		var p string
Russ Cox's avatar
Russ Cox committed
718
		switch std & stdMask {
719
		case stdYear:
720 721 722 723 724
			if len(value) < 2 {
				err = errBad
				break
			}
			p, value = value[0:2], value[2:]
725 726 727
			year, err = atoi(p)
			if year >= 69 { // Unix time starts Dec 31 1969 in some time zones
				year += 1900
728
			} else {
729
				year += 2000
730 731
			}
		case stdLongYear:
732
			if len(value) < 4 || !isDigit(value, 0) {
733 734
				err = errBad
				break
735
			}
736
			p, value = value[0:4], value[4:]
737
			year, err = atoi(p)
738
		case stdMonth:
739
			month, value, err = lookup(shortMonthNames, value)
740
		case stdLongMonth:
741
			month, value, err = lookup(longMonthNames, value)
742
		case stdNumMonth, stdZeroMonth:
743 744
			month, value, err = getnum(value, std == stdZeroMonth)
			if month <= 0 || 12 < month {
745 746 747
				rangeErrString = "month"
			}
		case stdWeekDay:
Rob Pike's avatar
Rob Pike committed
748 749
			// Ignore weekday except for error checking.
			_, value, err = lookup(shortDayNames, value)
750
		case stdLongWeekDay:
Rob Pike's avatar
Rob Pike committed
751
			_, value, err = lookup(longDayNames, value)
752
		case stdDay, stdUnderDay, stdZeroDay:
753 754 755
			if std == stdUnderDay && len(value) > 0 && value[0] == ' ' {
				value = value[1:]
			}
756 757
			day, value, err = getnum(value, std == stdZeroDay)
			if day < 0 || 31 < day {
758 759 760
				rangeErrString = "day"
			}
		case stdHour:
761 762
			hour, value, err = getnum(value, false)
			if hour < 0 || 24 <= hour {
763 764 765
				rangeErrString = "hour"
			}
		case stdHour12, stdZeroHour12:
766 767
			hour, value, err = getnum(value, std == stdZeroHour12)
			if hour < 0 || 12 < hour {
768 769 770
				rangeErrString = "hour"
			}
		case stdMinute, stdZeroMinute:
771 772
			min, value, err = getnum(value, std == stdZeroMinute)
			if min < 0 || 60 <= min {
773 774 775
				rangeErrString = "minute"
			}
		case stdSecond, stdZeroSecond:
776 777
			sec, value, err = getnum(value, std == stdZeroSecond)
			if sec < 0 || 60 <= sec {
778 779
				rangeErrString = "second"
			}
780 781
			// Special case: do we have a fractional second but no
			// fractional second in the format?
782
			if len(value) >= 2 && value[0] == '.' && isDigit(value, 1) {
783
				_, std, _ := nextStdChunk(layout)
Russ Cox's avatar
Russ Cox committed
784 785
				std &= stdMask
				if std == stdFracSecond0 || std == stdFracSecond9 {
786 787 788 789 790 791 792
					// Fractional second in the layout; proceed normally
					break
				}
				// No fractional second in the layout but we have one in the input.
				n := 2
				for ; n < len(value) && isDigit(value, n); n++ {
				}
793
				nsec, rangeErrString, err = parseNanoseconds(value, n)
794 795
				value = value[n:]
			}
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
		case stdPM:
			if len(value) < 2 {
				err = errBad
				break
			}
			p, value = value[0:2], value[2:]
			switch p {
			case "PM":
				pmSet = true
			case "AM":
				amSet = true
			default:
				err = errBad
			}
		case stdpm:
			if len(value) < 2 {
				err = errBad
				break
			}
			p, value = value[0:2], value[2:]
			switch p {
			case "pm":
				pmSet = true
			case "am":
				amSet = true
			default:
				err = errBad
			}
824
		case stdISO8601TZ, stdISO8601ColonTZ, stdNumTZ, stdNumShortTZ, stdNumColonTZ:
Russ Cox's avatar
Russ Cox committed
825
			if (std == stdISO8601TZ || std == stdISO8601ColonTZ) && len(value) >= 1 && value[0] == 'Z' {
826
				value = value[1:]
827
				z = UTC
828 829
				break
			}
830
			var sign, hour, min string
831 832 833 834 835 836 837 838 839
			if std == stdISO8601ColonTZ || std == stdNumColonTZ {
				if len(value) < 6 {
					err = errBad
					break
				}
				if value[3] != ':' {
					err = errBad
					break
				}
840
				sign, hour, min, value = value[0:1], value[1:3], value[4:6], value[6:]
841 842 843 844 845
			} else if std == stdNumShortTZ {
				if len(value) < 3 {
					err = errBad
					break
				}
846
				sign, hour, min, value = value[0:1], value[1:3], "00", value[3:]
847 848 849 850 851
			} else {
				if len(value) < 5 {
					err = errBad
					break
				}
852
				sign, hour, min, value = value[0:1], value[1:3], value[3:5], value[5:]
853
			}
854 855
			var hr, mm int
			hr, err = atoi(hour)
856
			if err == nil {
857
				mm, err = atoi(min)
858
			}
859
			zoneOffset = (hr*60 + mm) * 60 // offset is in seconds
860
			switch sign[0] {
861 862
			case '+':
			case '-':
863
				zoneOffset = -zoneOffset
Rob Pike's avatar
Rob Pike committed
864
			default:
865 866 867 868
				err = errBad
			}
		case stdTZ:
			// Does it look like a time zone?
869
			if len(value) >= 3 && value[0:3] == "UTC" {
870 871
				z = UTC
				value = value[3:]
872 873
				break
			}
874 875 876 877 878 879

			if len(value) >= 3 && value[2] == 'T' {
				p, value = value[0:3], value[3:]
			} else if len(value) >= 4 && value[3] == 'T' {
				p, value = value[0:4], value[4:]
			} else {
880
				err = errBad
881
				break
882 883 884 885 886 887 888 889 890 891
			}
			for i := 0; i < len(p); i++ {
				if p[i] < 'A' || 'Z' < p[i] {
					err = errBad
				}
			}
			if err != nil {
				break
			}
			// It's a valid format.
892
			zoneName = p
Russ Cox's avatar
Russ Cox committed
893

Russ Cox's avatar
Russ Cox committed
894
		case stdFracSecond0:
895 896 897 898 899 900 901 902 903
			// stdFracSecond0 requires the exact number of digits as specified in
			// the layout.
			ndigit := 1 + (std >> stdArgShift)
			if len(value) < ndigit {
				err = errBad
				break
			}
			nsec, rangeErrString, err = parseNanoseconds(value, ndigit)
			value = value[ndigit:]
Russ Cox's avatar
Russ Cox committed
904 905 906 907 908 909 910 911 912 913 914 915 916 917

		case stdFracSecond9:
			if len(value) < 2 || value[0] != '.' || value[1] < '0' || '9' < value[1] {
				// Fractional second omitted.
				break
			}
			// Take any number of digits, even more than asked for,
			// because it is what the stdSecond case would do.
			i := 0
			for i < 9 && i+1 < len(value) && '0' <= value[i+1] && value[i+1] <= '9' {
				i++
			}
			nsec, rangeErrString, err = parseNanoseconds(value, 1+i)
			value = value[1+i:]
918 919
		}
		if rangeErrString != "" {
Russ Cox's avatar
Russ Cox committed
920
			return Time{}, &ParseError{alayout, avalue, stdstr, value, ": " + rangeErrString + " out of range"}
921 922
		}
		if err != nil {
Russ Cox's avatar
Russ Cox committed
923
			return Time{}, &ParseError{alayout, avalue, stdstr, value, ""}
924 925 926 927 928 929 930 931 932 933 934 935 936
		}
	}
	if pmSet && hour < 12 {
		hour += 12
	} else if amSet && hour == 12 {
		hour = 0
	}

	if z != nil {
		return Date(year, Month(month), day, hour, min, sec, nsec, z), nil
	}

	if zoneOffset != -1 {
937
		t := Date(year, Month(month), day, hour, min, sec, nsec, UTC)
938 939 940 941
		t.sec -= int64(zoneOffset)

		// Look for local zone with the given offset.
		// If that zone was in effect at the given time, use it.
942
		name, offset, _, _, _ := local.lookup(t.sec + internalToUnix)
943
		if offset == zoneOffset && (zoneName == "" || name == zoneName) {
944
			t.loc = local
945
			return t, nil
946
		}
947 948 949 950

		// Otherwise create fake zone to record offset.
		t.loc = FixedZone(zoneName, zoneOffset)
		return t, nil
951
	}
952 953

	if zoneName != "" {
954
		t := Date(year, Month(month), day, hour, min, sec, nsec, UTC)
955 956
		// Look for local zone with the given offset.
		// If that zone was in effect at the given time, use it.
957
		offset, _, ok := local.lookupName(zoneName, t.sec+internalToUnix)
958
		if ok {
959 960 961
			t.sec -= int64(offset)
			t.loc = local
			return t, nil
962 963 964 965 966
		}

		// Otherwise, create fake zone with unknown offset.
		t.loc = FixedZone(zoneName, 0)
		return t, nil
967
	}
968

969 970
	// Otherwise, fall back to default.
	return Date(year, Month(month), day, hour, min, sec, nsec, defaultLocation), nil
971
}
972

973
func parseNanoseconds(value string, nbytes int) (ns int, rangeErrString string, err error) {
974
	if value[0] != '.' {
975 976
		err = errBad
		return
977
	}
978
	if ns, err = atoi(value[1:nbytes]); err != nil {
979
		return
980 981
	}
	if ns < 0 || 1e9 <= ns {
982 983
		rangeErrString = "fractional second"
		return
984 985 986 987 988 989 990 991 992 993
	}
	// We need nanoseconds, which means scaling by the number
	// of missing digits in the format, maximum length 10. If it's
	// longer than 10, we won't scale.
	scaleDigits := 10 - nbytes
	for i := 0; i < scaleDigits; i++ {
		ns *= 10
	}
	return
}
David Symonds's avatar
David Symonds committed
994 995 996 997

var errLeadingInt = errors.New("time: bad [0-9]*") // never printed

// leadingInt consumes the leading [0-9]* from s.
998
func leadingInt(s string) (x int64, rem string, err error) {
David Symonds's avatar
David Symonds committed
999 1000 1001 1002 1003 1004
	i := 0
	for ; i < len(s); i++ {
		c := s[i]
		if c < '0' || c > '9' {
			break
		}
1005
		if x >= (1<<63-10)/10 {
David Symonds's avatar
David Symonds committed
1006 1007 1008
			// overflow
			return 0, "", errLeadingInt
		}
1009
		x = x*10 + int64(c) - '0'
David Symonds's avatar
David Symonds committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
	}
	return x, s[i:], nil
}

var unitMap = map[string]float64{
	"ns": float64(Nanosecond),
	"us": float64(Microsecond),
	"µs": float64(Microsecond), // U+00B5 = micro symbol
	"μs": float64(Microsecond), // U+03BC = Greek letter mu
	"ms": float64(Millisecond),
	"s":  float64(Second),
	"m":  float64(Minute),
	"h":  float64(Hour),
}

// ParseDuration parses a duration string.
// A duration string is a possibly signed sequence of
// decimal numbers, each with optional fraction and a unit suffix,
// such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func ParseDuration(s string) (Duration, error) {
	// [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+
	orig := s
	f := float64(0)
	neg := false

	// Consume [-+]?
	if s != "" {
		c := s[0]
		if c == '-' || c == '+' {
			neg = c == '-'
			s = s[1:]
		}
	}
	// Special case: if all that is left is "0", this is zero.
	if s == "0" {
		return 0, nil
	}
	if s == "" {
		return 0, errors.New("time: invalid duration " + orig)
	}
	for s != "" {
		g := float64(0) // this element of the sequence

1054
		var x int64
David Symonds's avatar
David Symonds committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
		var err error

		// The next character must be [0-9.]
		if !(s[0] == '.' || ('0' <= s[0] && s[0] <= '9')) {
			return 0, errors.New("time: invalid duration " + orig)
		}
		// Consume [0-9]*
		pl := len(s)
		x, s, err = leadingInt(s)
		if err != nil {
			return 0, errors.New("time: invalid duration " + orig)
		}
		g = float64(x)
		pre := pl != len(s) // whether we consumed anything before a period

		// Consume (\.[0-9]*)?
		post := false
		if s != "" && s[0] == '.' {
			s = s[1:]
			pl := len(s)
			x, s, err = leadingInt(s)
			if err != nil {
				return 0, errors.New("time: invalid duration " + orig)
			}
			scale := 1
			for n := pl - len(s); n > 0; n-- {
				scale *= 10
			}
			g += float64(x) / float64(scale)
			post = pl != len(s)
		}
		if !pre && !post {
			// no digits (e.g. ".s" or "-.s")
			return 0, errors.New("time: invalid duration " + orig)
		}

		// Consume unit.
		i := 0
		for ; i < len(s); i++ {
			c := s[i]
			if c == '.' || ('0' <= c && c <= '9') {
				break
			}
		}
		if i == 0 {
			return 0, errors.New("time: missing unit in duration " + orig)
		}
		u := s[:i]
		s = s[i:]
		unit, ok := unitMap[u]
		if !ok {
			return 0, errors.New("time: unknown unit " + u + " in duration " + orig)
		}

		f += g * unit
	}

	if neg {
		f = -f
	}
	return Duration(f), nil
}