Module lessons (4/5)
The `time` package
The time package models three distinct concepts: instants (time.Time), durations (time.Duration) and periodic tools (timer, ticker). Distinguishing them is crucial: an instant is a point on the timeline, a duration is an interval.
time.Time — instants
now := time.Now() // current instant in the local timezone
utc := now.UTC() // same instant in UTC
later := now.Add(2 * time.Hour) // add a duration
diff := later.Sub(now) // 2h0m0s (it's a Duration)
fmt.Println(now.Year(), now.Month(), now.Day())
fmt.Println(now.Weekday())time.Time is immutable: all methods Add, Truncate, Round return a new Time.
To compare instants use Before, After, Equal. Do not use == if the instants can have different timezones/monotonic clocks.
time.Duration — intervals
d := 250 * time.Millisecond
fmt.Println(d) // 250ms
fmt.Println(d.Seconds()) // 0.25 (float64)
const timeout = 5 * time.Secondtime.Duration is an alias of int64 that counts nanoseconds. The constants time.Nanosecond, time.Microsecond, time.Millisecond, time.Second, time.Minute, time.Hour are of type Duration.
Parsing and formatting: the reference layout
Go does not use strings like YYYY-MM-DD. It uses a canonical reference instant:
Mon Jan 2 15:04:05 MST 2006i.e. 01/02 03:04:05PM '06 -0700. By memorizing this layout (mnemonic: 1-2-3-4-5-6-7) you can format any date:
const layout = "2006-01-02 15:04:05"
s := time.Now().Format(layout) // "2026-05-16 14:30:00"
t, err := time.Parse(layout, "2026-05-16 14:30:00")The stdlib offers ready-made layouts: time.RFC3339 ("2006-01-02T15:04:05Z07:00"), time.RFC1123, time.Kitchen ("3:04PM").
fmt.Println(time.Now().Format(time.RFC3339))Measuring time
start := time.Now()
work()
elapsed := time.Since(start) // = time.Now().Sub(start)
fmt.Println("ci ha messo", elapsed)time.Since uses the monotonic clock: it is not perturbed by system clock adjustments (NTP, daylight saving). For performance measurements that is what you want.
Timer and Ticker
time.After(d)returns achan time.Timethat receives only once afterd. Useful inselect:
select {
case res := <-ch:
fmt.Println("ok", res)
case <-time.After(2 * time.Second):
return errors.New("timeout")
}time.NewTimer(d)is a stoppable variant (t.Stop()).time.NewTicker(d)sends repeatedly everyd. Rememberdefer ticker.Stop()to avoid goroutine leaks.
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
fmt.Println("tick")
}Exercises
Print the current instant formatted according to time.RFC3339.
Solution available after 3 attempts
Measure how long a time.Sleep of 10ms takes using time.Since and print the result.
Solution available after 3 attempts
What type is the constant `time.Second`?
d := time.Second
// d ha tipo ???