Go📦Standard Libraryintermediate
time — Time and Duration
Go · Standard Library · Run with go run
Explanation
The `time` package represents moments (`time.Time`) and durations (`time.Duration`). Durations are `int64` nanoseconds with constants: `time.Second`, `time.Millisecond`, etc. `time.Now()` returns the current time. `time.Since(t)` returns elapsed duration. `time.After(d)` returns a channel that receives after duration — used for timeouts. `time.Parse` and `t.Format` use a reference time layout (`2006-01-02 15:04:05`).
Real-World Scenario
Measuring API latency: `start := time.Now()` before the call, `latency := time.Since(start)` after. Log `latency.Milliseconds()` to a metrics system.
Quick Snippet
snippet.go
import "time"
now := time.Now()
fmt.Println(now.Format("2006-01-02 15:04:05")) // Go's reference time
// Duration arithmetic
deadline := now.Add(30 * time.Second)
remaining := time.Until(deadline)
// Measure elapsed time
start := time.Now()
doWork()
elapsed := time.Since(start)
fmt.Printf("took %v\n", elapsed) // took 1.234ms
// Ticker — periodic events
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for t := range ticker.C {
fmt.Println("tick at", t)
}Full Example
time_basics.go
// Compile: go run time_basics.go
// Output (durations vary):
// formatted: 2024-01-15 10:30:00
// one hour later is after now: true
// elapsed under 1s: true
package main
import (
"fmt"
"time"
)
func main() {
// Go's reference time layout: Mon Jan 2 15:04:05 MST 2006
ref := time.Date(2024, 1, 15, 10, 30, 0, 0, time.UTC)
fmt.Println("formatted:", ref.Format("2006-01-02 15:04:05"))
now := time.Now()
later := now.Add(time.Hour)
fmt.Println("one hour later is after now:", later.After(now))
// Measure elapsed time
start := time.Now()
time.Sleep(10 * time.Millisecond)
elapsed := time.Since(start)
fmt.Println("elapsed under 1s:", elapsed < time.Second)
}
Run command
go run time_basics.go