Epoch
Unix epoch seconds and nanoseconds, converting back with time.Unix, and best practices for storing timestamps in databases.
The Unix epoch is the reference time January 1, 1970 at 00:00 UTC. Go can convert a time.Time value to a number of seconds or milliseconds since then. Keep track of which unit each number uses.
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 whether your program stores seconds or milliseconds. Both are integers, so mixing them can create a valid-looking but incorrect date. Convert to UTC, the shared zero-offset time standard, when a receiving system expects it. Format a timestamp only when displaying it to a person.