time.Duration
- Version
- 1.27
- Review
- Draft
Summary#
A time.Duration is an int64 count of nanoseconds. Write durations by multiplying a number by a unit constant. time.ParseDuration reads strings such as "300ms" or "2h45m".
Syntax#
timeout := 90 * time.Second
milliseconds := timeout.Milliseconds()
delay := time.Duration(count) * time.Millisecond
parsed, err := time.ParseDuration("1h30m")
Example#
package main
import (
"fmt"
"time"
)
func main() {
timeout := 90 * time.Second
fmt.Println(timeout, timeout.Seconds(), timeout.Milliseconds())
retries := 3
fmt.Println(time.Duration(retries) * 250 * time.Millisecond)
parsed, err := time.ParseDuration("1h15m30s")
fmt.Println(parsed, err)
fmt.Println(int64(parsed / time.Minute))
_, err = time.ParseDuration("2d")
fmt.Println(err)
}
Expected output#
1m30s 90 90000
750ms
1h15m30s <nil>
75
time: unknown unit "d" in duration "2d"
Common mistakes#
A bare number means nanoseconds: time.Sleep(5) asks for 5 ns. Convert an integer variable with time.Duration before multiplying by a unit. The package defines no day unit, which avoids confusion across daylight saving time transitions.
Version applicability#
Duration, the unit constants and ParseDuration date back to Go 1.0. The complete example requires Go 1.13 for Milliseconds. On earlier versions, use int64(timeout / time.Millisecond) to get whole milliseconds.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0