Skip to main content
Go offers extensive support for times and durations. Here are some examples of common time operations.

Getting Current Time

Get the current time:
now := time.Now()
fmt.Println(now)
// Output: 2026-03-03 10:15:30.123456789 +0000 UTC

Creating Time Values

Build a time struct by providing year, month, day, etc. Times are always associated with a Location (time zone):
then := time.Date(
    2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
fmt.Println(then)
// Output: 2009-11-17 20:34:58.651387237 +0000 UTC

Extracting Time Components

Extract various components of a time value:
fmt.Println(then.Year())
// Output: 2009

fmt.Println(then.Month())
// Output: November

fmt.Println(then.Day())
// Output: 17

fmt.Println(then.Weekday())
// Output: Tuesday

Comparing Times

Test if one time occurs before, after, or at the same time as another:
fmt.Println(then.Before(now))
// Output: true

fmt.Println(then.After(now))
// Output: false

fmt.Println(then.Equal(now))
// Output: false

Time Differences

The Sub method returns a Duration representing the interval between two times:
diff := now.Sub(then)
fmt.Println(diff)
// Output: 143520h45m31.876543211s

Duration Units

Compute the duration in various units:
fmt.Println(diff.Hours())
// Output: 143520.759...

fmt.Println(diff.Minutes())
// Output: 8611245.548...

fmt.Println(diff.Seconds())
// Output: 516674732.876...

fmt.Println(diff.Nanoseconds())
// Output: 516674732876543211

Time Arithmetic

Use Add to advance a time by a duration, or use a negative duration to move backwards:
fmt.Println(then.Add(diff))
// Output: 2026-03-03 10:15:30 +0000 UTC

fmt.Println(then.Add(-diff))
// Output: 1993-05-04 06:54:26.774231053 +0000 UTC

Common Time Methods

Returns the current local time
Creates a time value from components
Compare two time values
Returns the duration between two times
Adds a duration to a time

Epoch Time

Get Unix timestamps

Time Formatting

Format and parse time values

Package Reference

Build docs developers (and LLMs) love