How to Get Epoch Timestamps in Go
Working with epoch timestamps in Go. Get current Unix time, convert between time.Time and epoch, and handle nanosecond precision timestamps.
Programming
Detailed Explanation
Epoch Timestamps in Go
Go's time package provides clean, explicit methods for working with Unix timestamps. Go supports seconds, milliseconds, microseconds, and nanoseconds precision.
Getting the Current Epoch
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
// Seconds
fmt.Println(now.Unix()) // 1705312200
// Milliseconds
fmt.Println(now.UnixMilli()) // 1705312200000
// Microseconds
fmt.Println(now.UnixMicro()) // 1705312200000000
// Nanoseconds
fmt.Println(now.UnixNano()) // 1705312200000000000
}
Converting Epoch to time.Time
// From seconds
t := time.Unix(1705312200, 0)
fmt.Println(t.UTC()) // 2024-01-15 09:30:00 +0000 UTC
// From milliseconds
t = time.UnixMilli(1705312200000)
// From nanoseconds
t = time.Unix(0, 1705312200000000000)
Formatting
Go uses a unique reference time layout: Mon Jan 2 15:04:05 MST 2006
t := time.Unix(1705312200, 0).UTC()
// ISO 8601
fmt.Println(t.Format(time.RFC3339))
// "2024-01-15T09:30:00Z"
// Custom format
fmt.Println(t.Format("2006-01-02 15:04:05"))
// "2024-01-15 09:30:00"
Countdown Calculation
target := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
remaining := time.Until(target)
days := int(remaining.Hours()) / 24
hours := int(remaining.Hours()) % 24
minutes := int(remaining.Minutes()) % 60
seconds := int(remaining.Seconds()) % 60
fmt.Printf("%dd %dh %dm %ds\n", days, hours, minutes, seconds)
Best Practices
- Always use
time.UTC()when converting to/from epoch to avoid timezone bugs - Use
time.Unix()for seconds,time.UnixMilli()for milliseconds — never multiply manually - Go's zero value for
time.Timeis January 1, year 1, not the Unix epoch - Use
time.Durationfor intervals rather than raw integer arithmetic
Use Case
Reference this when building Go services that handle timestamps in APIs, databases, or message queues. Go's explicit Unix time methods prevent many common mistakes, but understanding the patterns is still essential for reliable time handling.