Go time Package
Working with Unix timestamps in Go using the time package. Covers time.Now(), Unix conversions, formatting with reference time, and duration math.
Language
time.Now().Unix()
Detailed Explanation
Go's time package provides a clean and well-designed API for working with timestamps. The central type is time.Time, which internally stores time with nanosecond precision as a wall clock reading and a monotonic clock reading.
Getting timestamps:
import "time"
// Current time as time.Time
now := time.Now()
// Unix timestamps at various precisions
now.Unix() // seconds: 1700000000
now.UnixMilli() // milliseconds: 1700000000000
now.UnixMicro() // microseconds: 1700000000000000
now.UnixNano() // nanoseconds: 1700000000000000000
Converting from Unix timestamp to time.Time:
// From seconds
t := time.Unix(1700000000, 0)
// From milliseconds
t := time.UnixMilli(1700000000000)
// From nanoseconds (second arg is nanosecond offset)
t := time.Unix(0, 1700000000000000000)
Go's unique formatting system:
Go uses a reference time instead of format specifiers like %Y-%m-%d. The reference time is Mon Jan 2 15:04:05 MST 2006 (which is 01/02 03:04:05 PM '06 -0700, a mnemonic for 1-2-3-4-5-6-7):
t.Format("2006-01-02T15:04:05Z07:00") // ISO 8601
t.Format(time.RFC3339) // predefined constant
t.Format("2006-01-02") // date only
t.Format("15:04:05") // time only
Duration arithmetic:
// Add 24 hours
tomorrow := now.Add(24 * time.Hour)
// Time between two instants
elapsed := time.Since(start) // time.Duration
elapsed.Seconds() // as float64
Common pitfalls:
Go's time.Time includes both a wall clock and monotonic clock component. The monotonic part ensures that time.Since() and time.Until() are not affected by clock adjustments (like NTP syncs). However, serializing to JSON or a database strips the monotonic reading. This is usually fine, but be aware that comparing a deserialized Time with time.Now() uses different clock sources internally.
Timezone handling: Use time.LoadLocation("America/New_York") to load IANA timezones. In Alpine-based Docker containers, the timezone database may be missing — install the tzdata package or embed it with import _ "time/tzdata" (Go 1.15+).
Use Case
Go backend services use time.Now().Unix() for generating cache keys, setting rate limiter windows, and attaching timestamps to structured log entries in cloud-native applications.