1
0
mirror of https://github.com/golang/go synced 2024-11-13 19:10:22 -07:00

time: add ISO 8601 time format

Fixes #431.

R=r, rsc
CC=golang-dev
https://golang.org/cl/179079
This commit is contained in:
Ben Olive 2009-12-17 13:39:13 -08:00 committed by Russ Cox
parent 95c776cca4
commit d2a835fbf3
2 changed files with 43 additions and 1 deletions

View File

@ -319,6 +319,9 @@ func format(t *Time, fmt string) string {
case 'M': // %M minute 00-59
decimal(buf[bp:bp+2], t.Minute)
bp += 2
case 'm': // %m month 01-12
decimal(buf[bp:bp+2], t.Month)
bp += 2
case 'S': // %S second 00-59
decimal(buf[bp:bp+2], t.Second)
bp += 2
@ -328,6 +331,20 @@ func format(t *Time, fmt string) string {
case 'y': // %y year 08
decimal(buf[bp:bp+2], int(t.Year%100))
bp += 2
case 'z': // %z tz in the form -0500
if t.ZoneOffset == 0 {
bp = addString(buf, bp, "Z")
} else if t.ZoneOffset < 0 {
bp = addString(buf, bp, "-")
decimal(buf[bp:bp+2], -t.ZoneOffset/3600)
decimal(buf[bp+2:bp+4], (-t.ZoneOffset%3600)/60)
bp += 4
} else {
bp = addString(buf, bp, "+")
decimal(buf[bp:bp+2], t.ZoneOffset/3600)
decimal(buf[bp+2:bp+4], (t.ZoneOffset%3600)/60)
bp += 4
}
case 'Z':
bp = addString(buf, bp, t.Zone)
default:
@ -355,6 +372,10 @@ func (t *Time) RFC850() string { return format(t, "%A, %d-%b-%y %H:%M:%S %Z") }
// RFC 1123: Sun, 06 Nov 1994 08:49:37 UTC
func (t *Time) RFC1123() string { return format(t, "%a, %d %b %Y %H:%M:%S %Z") }
// ISO8601 formats the parsed time value in the style of
// ISO 8601: 1994-11-06T08:49:37Z
func (t *Time) ISO8601() string { return format(t, "%Y-%m-%dT%H:%M:%S%z") }
// String formats the parsed time value in the style of
// date(1) - Sun Nov 6 08:49:37 UTC 1994
// date(1): Sun Nov 6 08:49:37 UTC 1994
func (t *Time) String() string { return format(t, "%a %b %e %H:%M:%S %Z %Y") }

View File

@ -101,6 +101,27 @@ func TestSecondsToUTCAndBack(t *testing.T) {
}
}
type TimeFormatTest struct {
time Time
formattedValue string
}
var iso8601Formats = []TimeFormatTest{
TimeFormatTest{Time{2008, 9, 17, 20, 4, 26, Wednesday, 0, "UTC"}, "2008-09-17T20:04:26Z"},
TimeFormatTest{Time{1994, 9, 17, 20, 4, 26, Wednesday, -18000, "EST"}, "1994-09-17T20:04:26-0500"},
TimeFormatTest{Time{2000, 12, 26, 1, 15, 6, Wednesday, 15600, "OTO"}, "2000-12-26T01:15:06+0420"},
}
func TestISO8601Conversion(t *testing.T) {
for _, f := range iso8601Formats {
if f.time.ISO8601() != f.formattedValue {
t.Error("ISO8601():")
t.Errorf(" want=%+v", f.formattedValue)
t.Errorf(" have=%+v", f.time.ISO8601())
}
}
}
func BenchmarkSeconds(b *testing.B) {
for i := 0; i < b.N; i++ {
Seconds()