Unix timestamps in Go
Get the current epoch time and convert between timestamps and dates in Go. Every snippet below is copy-ready.
// note
t.Unix() is seconds, t.UnixMilli() is milliseconds, both UTC-based.
now.go · current timestamp
now := time.Now()
seconds := now.Unix() // int64 seconds
millis := now.UnixMilli() // int64 milliseconds
timestamp → date
ts := int64(1700000000)
t := time.Unix(ts, 0).UTC()
fmt.Println(t.Format(time.RFC3339))
date → timestamp
t, err := time.Parse(time.RFC3339, "2023-11-14T22:13:20Z")
if err != nil {
log.Fatal(err)
}
ts := t.Unix()
// current epoch
— seconds since 1970-01-01T00:00:00Z.
Watch out for these
- Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
- Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
- Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.
Reference: https://pkg.go.dev/time