Get current time as formatted string in Go?

brianoh picture brianoh · May 4, 2011 · Viewed 159.1k times · Source

What's the best way to get the current timestamp in Go and convert to string? I need both date and time in eg. YYYYMMDDhhmmss format.

Answer

nmichaels picture nmichaels · May 4, 2011

Use the time.Now() function and the time.Format() method.

t := time.Now()
fmt.Println(t.Format("20060102150405"))

prints out 20110504111515, or at least it did a few minutes ago. (I'm on Eastern Daylight Time.) There are several pre-defined time formats in the constants defined in the time package.

You can use time.Now().UTC() if you'd rather have UTC than your local time zone.