BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Time Duration Values

Go 1.23

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".

Code Breakdown

11
Creating a duration. We multiply the integer '2' by the constant 'time.Hour'. This is the idiomatic way to create durations. 'd1' is now an int64 representing 2 hours in nanoseconds.
22
Adding duration to time. 'now.Add(total)' returns a NEW 'time.Time' object. 'time.Time' is immutable, so methods like Add/Sub return new values rather than modifying the receiver.
27
Calculating difference. 'future.Sub(now)' returns the duration between two time instants. The result is type 'time.Duration'.
33
Parsing duration strings. 'time.ParseDuration' is very powerful. It understands units like "ns", "us", "ms", "s", "m", "h". It's great for reading config files (e.g., "TIMEOUT=30s").