Parsing date string in Go

kannanrbk picture kannanrbk · Sep 15, 2014 · Viewed 212k times · Source

I tried parsing the date string "2014-09-12T11:45:26.371Z" in Go.

Code

layout := "2014-09-12T11:45:26.371Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout , str)

I got this error:

parsing time "2014-11-12T11:47:39.489Z": month out of range

How can I parse this date string?

Answer

RickyA picture RickyA · Sep 15, 2014

Use the exact layout numbers described here and a nice blogpost here.

so:

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

I know. Mind boggling. Also caught me first time. Go just doesn't use an abstract syntax for datetime components (YYYY-MM-DD), but these exact numbers (I think the time of the first commit of go Nope, according to this. Does anyone know?).