Go Gopher How to Go

The time package in Go provides functionality for measuring and displaying time. It includes support for time zones, durations, timers, tickers, and time formatting/parsing. Time values in Go are represented by the time.Time type, which includes both a wall clock reading and a monotonic clock reading for accurate duration measurements.

💡 Key Points

  • Time values are immutable and safe for concurrent use
  • Use monotonic clocks for measuring durations and intervals
  • Format and parse times using layout strings (not format specifiers)
  • The reference time is Mon Jan 2 15:04:05 MST 2006
  • Timers and tickers provide scheduling functionality
  • Always be aware of time zones when working with time
  • Use time.Duration for type-safe time intervals

Current Time and Basic Operations

Get the current time and perform basic time operations:

package main

import (
    "fmt"
    "time"
)

func main() {
    // Current time
    now := time.Now()
    fmt.Println("Current time:", now)
    
    // Time components
    fmt.Println("Year:", now.Year())
    fmt.Println("Month:", now. Month())
    fmt.Println("Day:", now.Day())
    fmt.Println("Hour:", now.Hour())
    
    // Unix timestamp
    fmt.Println("Unix:", now.Unix())
    fmt.Println("UnixNano:", now.UnixNano())
}
Output:
Current time: 2026-01-19 14:30:45.123456789 -0500 EST
Year: 2026
Month:  January
Day: 19
Hour:  14
Unix: 1737315045
UnixNano: 1737315045123456789

Formatting and Parsing

Format and parse times using layout strings:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    
    // Format time
    fmt. Println("RFC3339:", now.Format(time.RFC3339))
    fmt.Println("Custom:", now.Format("2006-01-02 15:04:05"))
    fmt.Println("Date only:", now.Format("Jan 2, 2006"))
    
    // Parse time
    timeStr := "2026-03-15 14:30:00"
    parsed, err := time.Parse("2006-01-02 15:04:05", timeStr)
    if err != nil {
        fmt.Println("Parse error:", err)
        return
    }
    fmt.Println("Parsed:", parsed)
}
Output:
RFC3339: 2026-01-19T14:30:45-05:00
Custom: 2026-01-19 14:30:45
Date only: Jan 19, 2026
Parsed: 2026-03-15 14:30:00 +0000 UTC

Durations and Time Arithmetic

Work with durations and perform time calculations:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    
    // Add duration
    future := now.Add(24 * time.Hour)
    fmt.Println("24 hours from now:", future. Format("2006-01-02 15:04:05"))
    
    // Subtract time
    past := now.Add(-48 * time.Hour)
    fmt.Println("48 hours ago:", past.Format("2006-01-02 15:04:05"))
    
    // Time difference
    diff := future.Sub(now)
    fmt.Println("Difference:", diff)
    fmt.Println("Hours:", diff.Hours())
    
    // Sleep
    fmt.Println("Sleeping...")
    time.Sleep(2 * time.Second)
    fmt.Println("Awake!")
}
Output:
24 hours from now: 2026-01-20 14:30:45
48 hours ago: 2026-01-17 14:30:45
Difference: 24h0m0s
Hours: 24
Sleeping...
Awake!

Time Creation Functions

FunctionExampleDescription
Nowtime.Now()Current local time
Datetime.Date(2026, 1, 15, 14, 30, 0, 0, time.UTC)Create specific time
Unixtime.Unix(1234567890, 0)From Unix timestamp
Parsetime.Parse(layout, value)Parse time from string
ParseInLocationtime.ParseInLocation(layout, value, loc)Parse with specific timezone

Duration Constants

ConstantValueExample
Nanosecond1 nanosecondtime. Nanosecond
Microsecond1000 nanosecondstime.Microsecond
Millisecond1000 microsecondstime.Millisecond
Second1000 millisecondstime.Second
Minute60 secondstime.Minute
Hour60 minutestime.Hour

Common Time Methods

MethodReturn TypeDescription
Add(d Duration)TimeAdd duration to time
Sub(t Time)DurationSubtract two times
Before(t Time)boolCheck if before another time
After(t Time)boolCheck if after another time
Equal(t Time)boolCheck if equal to another time
Format(layout string)stringFormat time as string
Unix()int64Unix timestamp in seconds
UnixNano()int64Unix timestamp in nanoseconds
Truncate(d Duration)TimeRound down to duration
Round(d Duration)TimeRound to nearest duration

Format Layout Components

ComponentLayout StringExample Output
Year20062026
Month (numeric)0101
Month (short)JanJan
Month (long)JanuaryJanuary
Day0219
Weekday (short)MonSun
Weekday (long)MondaySunday
Hour (12-hour)0302
Hour (24-hour)1514
Minute0430
Second0545
AM/PMPMPM
TimezoneMSTEST
Timezone offset-0700-0500

Timers and Tickers

TypeUsageDescription
Timertime.NewTimer(5 * time.Second)Single event after duration
AfterFunctime. AfterFunc(d, func())Execute function after duration
After<-time.After(d)Simple timer channel
Tickertime.NewTicker(1 * time.Second)Repeated events at interval
Ticktime. Tick(d)Simple ticker channel (no stop)

Common Time Patterns

PatternCodeUse Case
Timeoutselect { case <-time.After(5*time.Second): ... }Operation timeout
Ticker Loopticker := time.NewTicker(1*time.Second); for range ticker.C { ... }Periodic execution
Measure Durationstart := time.Now(); ...; elapsed := time.Since(start)Measure execution time
UTC Conversionutc := t.UTC()Convert to UTC timezone
Local Conversionlocal := t. Local()Convert to local timezone
Timezone Conversionloc, _ := time.LoadLocation("America/New_York"); t.In(loc)Convert to specific timezone
Start of Daytime.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())Truncate to midnight
Compare Timesif t1.Before(t2) { ... }Time comparison

Predefined Layouts

ConstantLayoutExample
ANSIC"Mon Jan _2 15:04:05 2006"Sun Jan 19 14:30:45 2026
RFC3339"2006-01-02T15:04:05Z07:00"2026-01-19T14:30:45-05:00
RFC822"02 Jan 06 15:04 MST"19 Jan 26 14:30 EST
Kitchen"3:04PM"2:30PM
DateTime"2006-01-02 15:04:05"2026-01-19 14:30:45
DateOnly"2006-01-02"2026-01-19
TimeOnly"15:04:05"14:30:45