Skip to content

Go Time and Epochs

Go offers extensive support for time and duration via the time package.

1. Basic Time

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    fmt.Println(now)

    // Build a specific time
    then := time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC)
    fmt.Println(then)

    // Components
    fmt.Println(then.Year())
    fmt.Println(then.Month())
    fmt.Println(then.Weekday())
}

2. Time Arithmetic

You can compare times or calculate the difference between them.

1
2
3
4
5
fmt.Println(then.Before(now)) // true
fmt.Println(then.After(now))  // false

diff := now.Sub(then)
fmt.Println(diff.Hours())

3. Epoch (Unix Time)

A common way to store time is as a "Unix timestamp"—the number of seconds since January 1, 1970.

1
2
3
4
5
6
7
8
now := time.Now()

fmt.Println(now.Unix())      // Seconds
fmt.Println(now.UnixMilli()) // Milliseconds
fmt.Println(now.UnixNano())  // Nanoseconds

// Convert back to a Time object
fmt.Println(time.Unix(now.Unix(), 0))

4. Durations

time.Duration represents an elapsed period of time.

d := 2 * time.Hour + 30 * time.Minute
fmt.Println(d.Minutes()) // 150

Why use the time package?

  1. Precision: Go's time.Time supports nanosecond precision.
  2. Monotonicity: Go uses "monotonic clocks" for measuring duration, making it safe from system clock jumps (like Leap Seconds or Daylight Savings changes).
  3. Standardization: Working with epochs is the standard for APIs and databases.