Epoch
Unix epoch seconds and nanoseconds, converting back with time.Unix, and best practices for storing timestamps in databases.
The Unix epoch is January 1, 1970 UTC. Go converts between time.Time and integer timestamps with methods whose units must be kept explicit.
Unix returns seconds, while UnixMilli returns milliseconds. Pass matching units to time.Unix or time.UnixMilli when converting back.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
seconds := now.Unix()
milliseconds := now.UnixMilli()
fmt.Println(seconds, milliseconds)
fmt.Println(time.Unix(seconds, 0).UTC())
fmt.Println(time.UnixMilli(milliseconds).UTC())
}In production
Choose and document one timestamp unit at storage and API boundaries; seconds and milliseconds are both int64, so confusing them can produce plausible but incorrect dates. UnixNano is undefined for times outside roughly 1678 to 2262. Convert to UTC when the consumer expects UTC, and format timestamps only where they are displayed.
Enjoyed this? Get more software craft delivered to your inbox.