Reputation: 6394
Go
prints time with
time.Now().String()
as
2012-12-18 06:09:18.6155554 +0200 FLEST
or
2009-11-10 23:00:00 +0000 UTC
http://play.golang.org/p/8qwq9U_Ri5
How do I parse it?
I guess FLEST
is Finland Latvian Estonian Standard Time
I am not in these countries and I guess I can get all kind of time zones.
I can't find one unified way or pattern to parse it with time.Parse
Upvotes: 10
Views: 10268
Reputation: 11113
Though time.Parse()
accepts a format string such as 2006-01-02 15:04:05 -0700 MST
, it may be simpler to use one of the constants defined in time.
const (
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"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
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"
// 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"
)
If you're using the strings as a way to store or encode time, (such as with a restrictive encoding format,) you may want to consider using Unix time. That way, you could just store an int64
(or two, if you keep the number of nanoseconds.
Upvotes: 12
Reputation: 28385
The documentation for time.String gives the format it uses: "2006-01-02 15:04:05.999999999 -0700 MST". A start would be to use the same format for parsing.
Time zones may be a problem for you though. If you must parse times that you know were produced with time.String, but were produced in other time zones, you must have the zoneinfo for the other time zones. See the documentation under LoadLocation. If you cannot obtain the zoneinfo, cannot install it on your system, or cannot risk failing on some new unknown time zone, then the time.String format is not for you. You will have to obtain time stamps in a different format, or remove the time zone from the strings and parse the modified strings with a modified format.
Upvotes: 5
Reputation: 17385
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now())
date := "2009-11-10 23:00:00 +0000 UTC"
t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", date)
if err != nil {
fmt.Println("parse error", err.Error())
}
fmt.Println(t.Format(time.ANSIC))
}
Playground: http://play.golang.org/p/hvqBgtesLd
See the source code at http://golang.org/src/pkg/time/format.go?s=15404:15450#L607
Upvotes: 10