Go by Example: Time Duration Values
Durations represent the elapsed time between two instants. Go uses `int64` nanoseconds for high precision. This example covers arithmetic, constants, and parsing duration strings.
Code
package main
import (
"fmt"
"time"
)
func main() {
// 1. Creating Durations
// Always use time constants (Second, Minute, etc.)
d1 := 2 * time.Hour
d2 := 30 * time.Minute
fmt.Println("Duration 1:", d1) // 2h0m0s
// 2. Arithmetic
// You can add/subtract durations
total := d1 + d2
fmt.Println("Total:", total) // 2h30m0s
// 3. Time Arithmetic
// Add a duration to a Time
now := time.Now()
future := now.Add(total)
fmt.Println("Future:", future)
// Subtraction (Time - Time = Duration)
diff := future.Sub(now)
fmt.Println("Diff:", diff)
// 4. ParseDuration
// Parses strings like "300ms", "-1.5h" or "2h45m"
// Valid units: ns, us, ms, s, m, h
parsed, err := time.ParseDuration("1h30m")
if err != nil {
panic(err)
}
fmt.Printf("Parsed: %.0f minutes\n", parsed.Minutes())
// 5. Converting to simple types
// Useful for APIs that expect int/float
seconds := total.Seconds() // float64
nanos := total.Nanoseconds() // int64
fmt.Printf("Seconds: %.2f, Nanos: %d\n", seconds, nanos)
}
Explanation
The time.Duration type in Go is a specialized integer type representing the elapsed time between two instants with nanosecond precision, stored internally as an int64. This high-resolution representation allows for extremely accurate timekeeping and arithmetic but requires developers to be mindful of type safety; arithmetic operations involving durations must typically use the provided constants like time.Second, time.Minute, or time.Hour to convert raw integer literals into meaningful time values (e.g., 5 * time.Second). This approach prevents common errors associated with "magic numbers" where units are ambiguous, ensuring that code remains readable and semantically correct.
Go's standard library provides a rich set of methods for manipulating durations, including arithmetic operations like Add and Sub on time.Time objects, as well as helper functions like ParseDuration which can decode human-readable strings such as "1h30m" or "300ms" into typed duration values. Furthermore, methods like Seconds(), Minutes(), and Hours() allow for easy conversion of these high-precision values into floating-point representations, which is often necessary when interfacing with external systems, metrics collectors, or JSON APIs that expect time intervals in specific units. Understanding the interplay between time.Time (an instant) and time.Duration (an interval) is fundamental to writing correct concurrent and time-sensitive Go programs.
- Nanosecond Precision: Base unit is nanoseconds.
- Constants: Always multiply by
time.Second, etc. - Arithmetic:
Time + Duration = Time;Time - Time = Duration. - Parsing: Supports complex strings like "1h15m30s".

