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
| Function | Example | Description |
| Now | time.Now() | Current local time |
| Date | time.Date(2026, 1, 15, 14, 30, 0, 0, time.UTC) | Create specific time |
| Unix | time.Unix(1234567890, 0) | From Unix timestamp |
| Parse | time.Parse(layout, value) | Parse time from string |
| ParseInLocation | time.ParseInLocation(layout, value, loc) | Parse with specific timezone |
Duration Constants
| Constant | Value | Example |
| Nanosecond | 1 nanosecond | time. Nanosecond |
| Microsecond | 1000 nanoseconds | time.Microsecond |
| Millisecond | 1000 microseconds | time.Millisecond |
| Second | 1000 milliseconds | time.Second |
| Minute | 60 seconds | time.Minute |
| Hour | 60 minutes | time.Hour |
Common Time Methods
| Method | Return Type | Description |
| Add(d Duration) | Time | Add duration to time |
| Sub(t Time) | Duration | Subtract two times |
| Before(t Time) | bool | Check if before another time |
| After(t Time) | bool | Check if after another time |
| Equal(t Time) | bool | Check if equal to another time |
| Format(layout string) | string | Format time as string |
| Unix() | int64 | Unix timestamp in seconds |
| UnixNano() | int64 | Unix timestamp in nanoseconds |
| Truncate(d Duration) | Time | Round down to duration |
| Round(d Duration) | Time | Round to nearest duration |
Format Layout Components
| Component | Layout String | Example Output |
| Year | 2006 | 2026 |
| Month (numeric) | 01 | 01 |
| Month (short) | Jan | Jan |
| Month (long) | January | January |
| Day | 02 | 19 |
| Weekday (short) | Mon | Sun |
| Weekday (long) | Monday | Sunday |
| Hour (12-hour) | 03 | 02 |
| Hour (24-hour) | 15 | 14 |
| Minute | 04 | 30 |
| Second | 05 | 45 |
| AM/PM | PM | PM |
| Timezone | MST | EST |
| Timezone offset | -0700 | -0500 |
Timers and Tickers
| Type | Usage | Description |
| Timer | time.NewTimer(5 * time.Second) | Single event after duration |
| AfterFunc | time. AfterFunc(d, func()) | Execute function after duration |
| After | <-time.After(d) | Simple timer channel |
| Ticker | time.NewTicker(1 * time.Second) | Repeated events at interval |
| Tick | time. Tick(d) | Simple ticker channel (no stop) |
Common Time Patterns
| Pattern | Code | Use Case |
| Timeout | select { case <-time.After(5*time.Second): ... } | Operation timeout |
| Ticker Loop | ticker := time.NewTicker(1*time.Second); for range ticker.C { ... } | Periodic execution |
| Measure Duration | start := time.Now(); ...; elapsed := time.Since(start) | Measure execution time |
| UTC Conversion | utc := t.UTC() | Convert to UTC timezone |
| Local Conversion | local := t. Local() | Convert to local timezone |
| Timezone Conversion | loc, _ := time.LoadLocation("America/New_York"); t.In(loc) | Convert to specific timezone |
| Start of Day | time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) | Truncate to midnight |
| Compare Times | if t1.Before(t2) { ... } | Time comparison |
Predefined Layouts
| Constant | Layout | Example |
| 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 |