Unix Timestamp in Go

In Go, time.Now().Unix() returns the current Unix time in seconds, and time.Unix(sec, nsec) builds a time.Time from a timestamp. time.Now().UnixNano() gives nanosecond precision.

Get & convert epoch time in Go

package main
import ("fmt"; "time")
func main() {
  fmt.Println(time.Unix(1700000000, 0).UTC()) // 2023-11-14T22:13:20.000Z
  fmt.Println(time.Now().Unix())
}
Gotcha: UnixNano() will overflow int64 around the year 2262 — fine for most uses, but worth knowing for far-future dates.

Frequently asked questions

How do I get the current Unix timestamp in Go?
time.Now().Unix() for seconds, time.Now().UnixMilli() for milliseconds, time.Now().UnixNano() for nanoseconds.
How do I convert a Unix timestamp to time.Time?
time.Unix(seconds, 0).UTC() returns the instant in UTC.

Other languages

Copied