time.Duration
time.Duration represents a elapsed time as an int64 nanosecond count. It provides safe arithmetic and prevents unit confusion.
time.Duration prevents unit confusion — you cannot accidentally add seconds to milliseconds. Use time.Second, time.Millisecond, time.Microsecond as multipliers. ParseDuration converts strings to durations.
Monotonic Clock
time.Time contains both a wall clock and a monotonic clock. The monotonic clock is immune to system time adjustments. Use it for measuring elapsed time.
Gomonotonic-clock-usage.go
time.Since and time.Sub use the monotonic clock, which is immune to NTP adjustments and manual time changes. This makes duration measurements accurate and consistent. time.Now() includes a monotonic reading automatically.
Timers
time.NewTimer creates a reusable timer. Always Stop() timers to prevent leaks. Reset() reuses a stopped timer. time.AfterFunc runs a function after a delay. time.After creates a one-shot channel — avoid in loops.
Tickers
Tickers fire at regular intervals. defer ticker.Stop() prevents leaks. Jittered tickers prevent thundering herd. Missed tick patterns process immediately — they do not queue up missed ticks.
Deadline Calculations
time.Until calculates time remaining. context.WithDeadline sets an absolute deadline. Check ctx.Deadline() to see the deadline. Retry loops should check the deadline before retrying.
Go uses a reference time: Mon Jan 2 15:04:05 MST 2006. Format strings are based on this reference. time.RFC3339 is the standard for API timestamps. Always use UTC for storage and display.
Store and display times in UTC. Convert to local time only for user-facing display. This prevents timezone bugs and DST transitions from causing issues. Use time.UTC as the location.