← Back to Articles

Unix Timestamps in Go (Golang)

Go's time package has excellent built-in support for Unix timestamps. Here are the most common patterns you'll need when building Go applications that work with epoch time.

Get the current Unix timestamp

Use time.Now().Unix() for seconds or time.Now().UnixMilli() for milliseconds.

package main

import (
    "fmt"
    "time"
)

func main() {
    // Seconds since epoch
    fmt.Println(time.Now().Unix())

    // Milliseconds since epoch (Go 1.17+)
    fmt.Println(time.Now().UnixMilli())

    // Nanoseconds since epoch
    fmt.Println(time.Now().UnixNano())
}
AdSense — In-Article Banner

Convert a Unix timestamp to time.Time

time.Unix(sec, nsec) converts a Unix timestamp back to a time.Time value you can format and manipulate.

// From seconds (nsec = 0)
t := time.Unix(1700000000, 0)
fmt.Println(t.UTC().Format(time.RFC3339))
// Output: 2023-11-14T22:13:20Z

// From milliseconds
ms := int64(1700000000000)
t2 := time.Unix(ms/1000, (ms%1000)*int64(time.Millisecond))
fmt.Println(t2.UTC().Format(time.RFC3339))

Format and timezone handling

Go uses reference time Mon Jan 2 15:04:05 MST 2006 for formatting. Always use .UTC() when you need timezone-consistent output.

t := time.Unix(1700000000, 0).UTC()

// Common formats
fmt.Println(t.Format(time.RFC3339))        // 2023-11-14T22:13:20Z
fmt.Println(t.Format("2006-01-02"))        // 2023-11-14
fmt.Println(t.Format("2006-01-02 15:04:05")) // 2023-11-14 22:13:20
AdSense — In-Article Banner