Golang Unix Timestamps: time.Unix(), UnixMilli() & Nanoseconds
Formatting dates in Go trips up newcomers who write YYYY-MM-DD and wonder why their logs literally print the letters "YYYY". Go rejects percentage tokens like %Y and uses a fixed reference date instead, while offering crisp int64 epoch methods from seconds down to nanoseconds.
Get Current Epoch Values in Go
Since Go 1.17, the standard time package provides direct methods for seconds, milliseconds, microseconds, and nanoseconds. All four return signed 64-bit integers (int64).
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("Seconds:", now.Unix())
fmt.Println("Milliseconds:", now.UnixMilli())
fmt.Println("Microseconds:", now.UnixMicro())
fmt.Println("Nanoseconds:", now.UnixNano())
}
Convert Unix Timestamps Back to time.Time
Use time.Unix(sec, nsec) for seconds or nanoseconds, and time.UnixMilli(ms) for 13-digit JavaScript values. Chain .UTC() or .In(loc) to control output formatting.
tSec := time.Unix(1764892800, 0).UTC()
tMs := time.UnixMilli(1764892800500).UTC()
tNs := time.Unix(0, 1764892800123456789).UTC()
loc, _ := time.LoadLocation("America/New_York")
fmt.Println(tSec.In(loc).Format(time.RFC3339))
Go's Reference Time Rule and Nanosecond Limits
Custom Go formats always use the exact reference moment: Mon Jan 2 15:04:05 MST 2006 (for example, "2006-01-02 15:04:05"). For APIs, use the built-in time.RFC3339 constant instead of typing a layout string manually.
Watch out for one limit on UnixNano(): because an int64 nanosecond counter covers roughly 292 years before and after 1970, calling UnixNano() on dates outside the years 1677 to 2262 is undefined in the Go time package documentation. Use Unix() for historical or far-future dates.
Wall Clock vs Monotonic Clock for Benchmarks
When measuring how long an HTTP handler takes in Go, time.Now() attaches an internal monotonic clock reading automatically. Subtracting two times with time.Since(start) remains accurate even if NTP adjusts the server wall clock backward during the request.