time: instants, durations and timers
time has two kinds of value: an instant, which is a time.Time, and a span, which is a time.Duration and is just an int64 of nanoseconds with a good String method. Timers and tickers are channels, so waiting for time is the same select as waiting for a goroutine. This lesson uses durations and timers; the next formats and parses instants.
Duration arithmetic
A duration is written with a unit and multiplied as a number: 90 * time.Minute. Its string form is the shortest that reads well, and the conversion methods return floats because an hour does not divide evenly into every span. Truncate rounds down to a unit, which is how a report groups measurements.
package main
import (
"fmt"
"time"
)
func main() {
d := 90 * time.Minute
fmt.Println("duration:", d)
fmt.Println("hours:", d.Hours())
fmt.Println("minutes:", d.Minutes())
fmt.Println("seconds:", d.Seconds())
fmt.Println("truncated:", d.Truncate(time.Hour))
}
go build -o app main.go && ./app
duration: 1h30m0s
hours: 1.5
minutes: 90
seconds: 5400
truncated: 1h0m0s
The string form uses h, m and s and drops a zero part; a duration under a second prints in milliseconds or microseconds. Truncate went down to the hour, and Round would have gone to the nearest one; both are exact and neither allocates.
Sleep and timers
time.Sleep blocks the goroutine and not the thread, and time.NewTimer gives a channel that fires once. A timer can be stopped before it fires; stopping it after it fired returns false, because the value is already in the channel, which is the detail below. A long sleep in a server is a bug, and a timer with a select is the usual replacement.
package main
import (
"fmt"
"time"
)
func main() {
timer := time.NewTimer(10 * time.Millisecond)
<-timer.C
fmt.Println("timer fired")
start := time.Now()
time.Sleep(20 * time.Millisecond)
fmt.Println("slept at least 20ms:", time.Since(start) >= 20*time.Millisecond)
fmt.Println("stopped after firing:", timer.Stop())
}
go build -o app main.go && ./app
timer fired
slept at least 20ms: true
stopped after firing: false
The comparison with a duration is exact in the program and true in the run, because the sleep is a minimum and the clock is monotonic. The false from Stop means the timer had already delivered its value; a program that needs to know whether it won the race uses the return value, and the rest of the time it just stops the timer in a defer.
A ticker
A ticker sends a value on every interval until it is stopped, and it drops ticks when the receiver is slow rather than queueing them. The loop below counts three ticks and checks that at least three intervals passed, which is the useful assertion for a ticker: the exact time varies, the order of magnitude does not. The 100 millisecond case is a guard so a broken ticker fails the program instead of hanging it.
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(5 * time.Millisecond)
defer ticker.Stop()
count := 0
start := time.Now()
for {
select {
case <-ticker.C:
count++
if count == 3 {
fmt.Println("ticks:", count)
fmt.Println("elapsed at least 15ms:", time.Since(start) >= 15*time.Millisecond)
return
}
case <-time.After(100 * time.Millisecond):
fmt.Println("timeout")
return
}
}
}
go build -o app main.go && ./app
ticks: 3
elapsed at least 15ms: true
Three ticks at five milliseconds are at least fifteen milliseconds, and the run took that long. A ticker is the clock of a rate limiter, a metrics flush or a heartbeat; a timer is the clock of a deadline. The difference is one value against a stream, and the stop is required for both.
Dates and Add
time.Date builds an instant from its parts in a location, and Add moves it by a duration while AddDate moves it by calendar units. The difference matters across a month boundary and across a daylight-saving change: Add(24h) is always the next day in UTC and not always in a zone.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC)
fmt.Println("date:", t.Format("2006-01-02"))
fmt.Println("after:", t.Add(48*time.Hour).Format("2006-01-02"))
fmt.Println("before:", t.AddDate(0, -1, 0).Format("2006-01-02"))
}
go build -o app main.go && ./app
date: 2026-11-18
after: 2026-11-20
before: 2026-10-18
Forty-eight hours added two days, and minus one month moved the date back a month with the day kept. The layout string is the next lesson; the important part here is that a date is a time.Time in a location, and AddDate is the one that knows about months.
Monotonic time
A time.Time from time.Now carries a monotonic reading as well as a wall clock, and time.Since uses the monotonic part when both ends have it. That is why elapsed measurements stay right when the system clock is adjusted, and why a timestamp should be stored as UTC and only formatted for a user. A time that was parsed or built by time.Date has no monotonic reading, so a comparison with Before uses the wall clock for those.
Two rules follow. Never compare wall-clock timestamps for elapsed time; measure with Since. And never build a duration by subtracting two Unix() values, because the result loses the sub-second part and the monotonic clock.
Exercises
- Round the ninety minutes to the nearest hour instead of truncating. What does the string print, and why is Round different from Truncate here?
- Stop the timer before it fires and print the result. Then read from timer.C anyway: what does it return, and how long does the read block?
- Change the ticker interval to 20 milliseconds and run it. What does the elapsed check print, and what does the timeout guard protect against?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a time.Duration?
Answer
An int64 count of nanoseconds with a String method
Arithmetic and conversion are on that integer.
-
What does 90 * time.Minute print as?
Answer
1h30m0s
The string drops zero parts but keeps the seconds.
-
Does time.Sleep block the OS thread?
Answer
No, it parks the goroutine and the thread runs other work
The runtime multiplexes goroutines on threads.
-
What does Timer.Stop return after the timer fired?
Answer
false
The value is already in the channel.
-
What does a Ticker do when the receiver is slow?
Answer
Drops ticks
The channel has room for one tick.
-
What does AddDate change that Add does not?
Answer
Calendar units such as months and years
A month is not a fixed duration.
-
Why is time.Since better than subtracting Unix seconds?
Answer
It uses the monotonic clock and keeps sub-second precision
A wall-clock adjustment does not affect it.
-
Which values carry a monotonic reading?
Answer
Those from time.Now in the same process
Parsed and constructed times have only a wall clock.
-
What unit does Duration store?
Answer
Nanoseconds
time.Second is a billion of them.
-
What does Truncate(time.Hour) do to 90 minutes?
Answer
Returns 1h0m0s
It rounds down to the unit.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev