Reputation: 32005
When you execute the following code snippet, which is derived mainly from Go's time package documentation and its Parse function example:
package main
import (
"time"
"fmt"
)
var shortForm = "2006-Jan-02"
t, _ := time.Parse(shortForm, "2013-Feb-03")
fmt.Println(t)
Then, you can get the correct result, 2013-02-03 00:00:00 +0000 UTC
, in your console.
However, when you change the shortForm
value slightly, such as 2007-Jan-02
, 2006-Feb-02
, or 2006-Jan-01
, it outputs wrong results, and the output looks not even regularly, such as 0001-01-01 00:00:00 +0000 UTC
, 2013-03-01 00:00:00 +0000 UTC
, or 2013-01-03 00:00:00 +0000 UTC
.
So why does the function behave such strangely? And how can I deal with it? Every time I use the function, should I always define layout variable as 2006-Jan-02
?
Thanks.
Upvotes: 5
Views: 682
Reputation: 43949
The time.Parse
and time.Format
functions use the numbers in the layout argument to identify which date component is referred to:
1
: month (alternatively can appear in words as Jan
/ January
)2
: day3
: hour (alternatively as 15
for 24 hour clock)4
: minute5
: second6
: year (alternatively as 2006
for 4 digit year)7
: time zone (alternatively as MST
for time zone code).So when you change the layout string from 2006-Jan-02
to 2006-Jan-01
, you are saying that the month is represented in the time string twice, leading to unexpected results.
Upvotes: 7