I tried parsing date string "2014-09-12T11:45:26.371Z" in go lang.
Code
layout := "2014-09-12T11:45:26.371Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout , str)
parsing time "2014-11-12T11:47:39.489Z": month out of range
I got this error.
How to parse this date string?
As answered but to save typing out
"2006-01-02T15:04:05.000Z"
for the layout, you could use the package's constant RFC3339.https://play.golang.org/p/Dgu2ZvHwTh
I will suggest using time.RFC3339 constant from time package. You can check other constants from time package. https://golang.org/pkg/time/#pkg-constants
The layout to use is indeed "
2006-01-02T15:04:05.000Z
" described in RickyA's answer.It isn't "the time of the first commit of go", but rather a mnemonic way to remember said layout.
See pkg/time:
(1,2,3,4,5,6,7, provided you remember that 1 is for the month, and 2 for the day, which is not easy for an European like myself, used to the day-month date format)
As illustrated in "time.parse : why does golang parses the time incorrectly?", that layout (using 1,2,3,4,5,6,7) must be respected exactly.
This might be super late, but this is for people that might stumble on this problem and might want to use external package for parsing date string.
I've tried looking for a libraries and I found this one:
https://github.com/araddon/dateparse
Example from the README:
This is rather late to the party, and not really saying anything that hasn't been already said in one form or another, mostly through links above, but I wanted to give a TL;DR recap to those with less attention span:
The date and time of the go format string is very important. It's how Go knows which field is which. They are generally 1-9 left to right as follows:
So, Don't write "01-05-15" as your date format, unless you want "Month-Second-Hour"
(... again, this was basically a summary of above.)
Use the exact layout numbers described here and a nice blogpost here.
so:
gives:
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 goNope, according to this. Does anyone know?).