time package conventions. Working examples for every common operation — get current time, convert epoch to date, convert date to epoch, format display, parse, and handle timezones.
Go's `time.Now()` returns a `time.Time`. Convert to Unix with `.Unix()`, `.UnixMilli()`, etc.
import "time"
now := time.Now().Unix()
// → 1735689600 (int64)
now := time.Now().UnixMilli()
// → 1735689600000
now := time.Now().UnixMicro() // microseconds
nowNs := time.Now().UnixNano() // nanoseconds
Use `time.Unix(seconds, nanoseconds)` to construct from epoch. The second arg is nanoseconds within that second.
import "time"
t := time.Unix(1735689600, 0)
fmt.Println(t.UTC().Format(time.RFC3339))
// → 2025-01-01T00:00:00Z
t := time.UnixMilli(1735689600000)
// or manually:
t2 := time.Unix(0, 1735689600000 * int64(time.Millisecond))
loc, _ := time.LoadLocation("America/New_York")
t := time.Unix(1735689600, 0).In(loc)
fmt.Println(t)
// → 2024-12-31 19:00:00 -0500 EST
Every `time.Time` has `.Unix()` and friends. The result is timezone-independent (Unix time is always UTC).
time.Now().Unix()
t := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
t.Unix()
// → 1735689600
t, err := time.Parse(time.RFC3339, "2025-01-01T00:00:00Z")
if err == nil {
fmt.Println(t.Unix())
}
Go's format strings use the reference time `Mon Jan 2 15:04:05 MST 2006` instead of strftime-style. The standard library provides constants like `time.RFC3339`.
now := time.Now()
fmt.Println(now.Format(time.RFC3339)) // 2025-01-01T12:34:56-05:00
fmt.Println(now.Format(time.RFC822)) // 01 Jan 25 12:34 EST
fmt.Println(now.Format(time.UnixDate)) // Wed Jan 1 12:34:56 EST 2025
// Use the reference time: Mon Jan 2 15:04:05 MST 2006
now.Format("2006-01-02 15:04:05") // 2025-01-01 12:34:56
Use `time.Parse(layout, value)` with one of the standard layout constants, or a custom one.
t, err := time.Parse(time.RFC3339, "2025-01-01T00:00:00Z")
if err != nil {
log.Fatal(err)
}
fmt.Println(t.Unix())
t, err := time.Parse("2006-01-02", "2025-01-01")
// Date-only, parsed as UTC midnight
loc, _ := time.LoadLocation("America/New_York")
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2025-01-01 12:00:00", loc)
Go-specific date pitfalls.
// Go uses 2006-01-02 15:04:05 -0700 as a layout reference
// "1 2 3 4 5 6 7" in time order is: Jan 2, 15:04 PM, year 2006, MST
// The numbers are not arbitrary — they correspond to those positions.
// var t time.Time is the zero value, not nil.
// Check with t.IsZero() instead of t == nil.
var t time.Time
if t.IsZero() {
fmt.Println("not set")
}
// time.Parse returns an error — don't ignore it.
// Bad date strings silently produce time.Time{} otherwise.
Need to quickly check what a specific timestamp converts to? Use the main converter — paste any value and get every format back.
Working with many timestamps at once? Try the batch converter — paste a list, get a CSV or JSON file back.