Unix Timestamp in Go
Go's time package provides clean, idiomatic ways to work with Unix timestamps.
Get the current Unix timestamp
Go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println(now.Unix()) // seconds: 1700000000
fmt.Println(now.UnixMilli()) // milliseconds: 1700000000000
fmt.Println(now.UnixMicro()) // microseconds
fmt.Println(now.UnixNano()) // nanoseconds
}Convert epoch to time.Time
Go
// From seconds
t := time.Unix(1700000000, 0)
fmt.Println(t.UTC()) // 2023-11-14 22:13:20 +0000 UTC
// From milliseconds
ms := int64(1700000000000)
t = time.UnixMilli(ms)
// From nanoseconds
ns := int64(1700000000000000000)
t = time.Unix(0, ns)Convert time.Time to epoch
Go
t, _ := time.Parse(time.RFC3339, "2023-11-14T22:13:20Z")
fmt.Println(t.Unix()) // 1700000000
fmt.Println(t.UnixMilli()) // 1700000000000Format timestamps
Go
t := time.Unix(1700000000, 0).UTC()
// Go uses a reference time: Mon Jan 2 15:04:05 MST 2006
t.Format(time.RFC3339) // "2023-11-14T22:13:20Z"
t.Format(time.RFC1123) // "Tue, 14 Nov 2023 22:13:20 UTC"
t.Format("2006-01-02 15:04:05") // "2023-11-14 22:13:20"
t.Format("02/01/2006") // "14/11/2023"Timezones
Go
t := time.Unix(1700000000, 0)
// Convert to a specific timezone
loc, _ := time.LoadLocation("Asia/Kolkata")
tIST := t.In(loc)
fmt.Println(tIST.Format("2006-01-02 15:04:05 MST")) // 2023-11-15 03:43:20 IST
loc2, _ := time.LoadLocation("America/New_York")
fmt.Println(t.In(loc2).Format(time.RFC3339)) // 2023-11-14T17:13:20-05:00Time arithmetic
Go
now := time.Now()
future := now.Add(24 * time.Hour) // 1 day later
past := now.Add(-7 * 24 * time.Hour) // 7 days ago
// Duration between two times
diff := future.Sub(past)
fmt.Println(diff.Hours()) // 192
// Check if expired
expiry := time.Unix(1700000000, 0)
if time.Now().After(expiry) {
fmt.Println("expired")
}→ Use the live epoch converter to convert any Go timestamp instantly.