Time and Scheduling

Overview

The time package provides functionality for measuring and displaying time.

Current Time

now := time.Now()
fmt.Println(now)  // 2024-01-15 10:30:00 -0500 EST

Duration

d := 5 * time.Second
d := time.Minute + 30*time.Second
d := time.ParseDuration("1h30m")

Sleeping

time.Sleep(2 * time.Second)

Timers

// One-shot timer
timer := time.NewTimer(5 * time.Second)
<-timer.C  // Blocks until timer fires

// Cancel timer
if !timer.Stop() {
    <-timer.C
}

Tickers

ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()

for t := range ticker.C {
    fmt.Println("Tick at", t)
}

Formatting

// Format uses reference time: Mon Jan 2 15:04:05 MST 2006
now := time.Now()
fmt.Println(now.Format("2006-01-02"))           // 2024-01-15
fmt.Println(now.Format("15:04:05"))             // 10:30:00
fmt.Println(now.Format(time.RFC3339))           // 2024-01-15T10:30:00-05:00

Parsing

t, err := time.Parse("2006-01-02", "2024-01-15")
t, err := time.Parse(time.RFC3339, "2024-01-15T10:30:00Z")

Time Zones

loc, _ := time.LoadLocation("America/New_York")
t := time.Now().In(loc)

utc := time.Now().UTC()

Comparisons

t1.Before(t2)
t1.After(t2)
t1.Equal(t2)
t1.Sub(t2)    // Duration between
t1.Add(d)     // Add duration

Summary

Type/Function Purpose
time.Now() Current time
time.Duration Time interval
time.Timer One-shot delay
time.Ticker Repeated intervals
time.Format() Time to string
time.Parse() String to time