time represents instants, durations, and calendar dates, and drives everything that waits, sleeps, or times out.
Examples
Since and Sub measure elapsed time. Comparing two Times with Sub returns a Duration directly usable in arithmetic or formatting.
start := time.Now()
time.Sleep(10 * time.Millisecond)
elapsed := time.Since(start)
fmt.Println(elapsed > 0)
t1 := time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC)
t2 := time.Date(2024, time.January, 2, 0, 0, 0, 0, time.UTC)
fmt.Println(t2.Sub(t1))
fmt.Println(t1.Before(t2))Output
true
24h0m0s
trueGo formats and parses dates against a specific reference time instead of strftime-style verbs. Format and Parse are exact inverses of each other for a given layout.
t := time.Date(2024, time.March, 15, 9, 30, 0, 0, time.UTC)
fmt.Println(t.Format(time.RFC3339))
fmt.Println(t.Format("Jan 2, 2006"))
parsed, err := time.Parse(time.RFC3339, "2024-03-15T09:30:00Z")
fmt.Println(parsed.Equal(t), err)Output
2024-03-15T09:30:00Z
Mar 15, 2024
true NewTimer exposes its channel as a field, so it can sit in a select alongside other cases. time.After is the same mechanism packaged as a one-line expression.
timer := time.NewTimer(10 * time.Millisecond)
<-timer.C
fmt.Println("timer fired")
select {
case <-time.After(10 * time.Millisecond):
fmt.Println("after fired")
}Output
timer fired
after firedParseDuration and the Hours/Minutes accessors move between the string form and numeric units. Round follows Go's tie-away-from-zero rule at an exact halfway point.
d, err := time.ParseDuration("1h30m")
fmt.Println(d, err)
fmt.Println(d.Hours())
fmt.Println(d.Minutes())
rounded := d.Round(time.Hour)
fmt.Println(rounded)Output
1h30m0s
1.5
90
2h0m0s Creating times & durations
| Function | Description |
|---|---|
Now() Time t := time.Now() | Returns the current local time |
Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC) | Constructs a Time from calendar and clock components |
Unix(sec, nsec int64) Time time.Unix(1700000000, 0) | Constructs a Time from a Unix timestamp in seconds and nanoseconds |
UnixMilli(msec int64) Time time.UnixMilli(1700000000000) | Constructs a Time from a Unix timestamp in milliseconds |
UnixMicro(usec int64) Time time.UnixMicro(1700000000000000) | Constructs a Time from a Unix timestamp in microseconds |
Parse(layout, value string) (Time, error) time.Parse(time.RFC3339, "2024-01-01T00:00:00Z") | Parses value according to a reference-time layout string |
ParseInLocation(layout, value string, loc *Location) (Time, error) time.ParseInLocation("2006-01-02", "2024-01-01", loc) | Like Parse, but interprets value in loc when the layout has no zone |
ParseDuration(s string) (Duration, error) time.ParseDuration("1h30m") | Parses a duration string such as "1h30m" or "500ms" |
LoadLocation(name string) (*Location, error) time.LoadLocation("America/New_York") | Loads a named time zone, such as "America/New_York" |
FixedZone(name string, offset int) *Location time.FixedZone("UTC-5", -5*3600) | Creates a Location with a fixed offset from UTC, in seconds |
Time methods
| Function | Description |
|---|---|
Year() / Month() / Day() t.Year() | Calendar date components of t |
Hour() / Minute() / Second() / Nanosecond() t.Hour() | Clock components of t |
Weekday() Weekday t.Weekday() | Day of the week t falls on |
Format(layout string) string t.Format(time.RFC3339) | Formats t using a reference-time layout string |
Add(d Duration) Time t.Add(time.Hour) | Returns t offset by d |
AddDate(years, months, days int) Time t.AddDate(1, 0, 0) | Returns t offset by a calendar interval, handling month/year overflow |
Sub(u Time) Duration t.Sub(u) | Returns the duration t-u |
Before(u Time) / After(u Time) bool t.Before(u) | Reports whether t is ordered before or after u |
Equal(u Time) bool t.Equal(u) | Reports whether t and u represent the same instant, unlike == |
IsZero() bool t.IsZero() | Reports whether t is the zero Time value |
UTC() / Local() / In(loc *Location) Time t.UTC() | Returns t with its location changed; the instant itself is unchanged |
Unix() / UnixMilli() / UnixMicro() / UnixNano() int64 t.Unix() | t expressed as a Unix timestamp at the given precision |
Truncate(d Duration) / Round(d Duration) Time t.Truncate(time.Hour) | Rounds t down, or to the nearest, multiple of d since the zero time |
String() string t.String() | Default human-readable representation of t |
Timers, tickers & sleeping
| Function | Description |
|---|---|
Sleep(d Duration) time.Sleep(time.Second) | Pauses the current goroutine for at least d |
Since(t Time) Duration time.Since(start) | Shorthand for time.Now().Sub(t) |
Until(t Time) Duration time.Until(deadline) | Shorthand for t.Sub(time.Now()) |
After(d Duration) <-chan Time <-time.After(time.Second) | Returns a channel that receives once, after d elapses |
Tick(d Duration) <-chan Time for range time.Tick(time.Second) { } | Returns a channel that receives repeatedly every d; leaks if never stopped |
NewTimer(d Duration) *Timer t := time.NewTimer(time.Second) | Creates a Timer whose C channel receives once after d |
NewTicker(d Duration) *Ticker t := time.NewTicker(time.Second) | Creates a Ticker whose C channel receives repeatedly every d |
AfterFunc(d Duration, f func()) *Timer time.AfterFunc(time.Second, cleanup) | Runs f in its own goroutine after d elapses |
(*Timer) Stop() bool timer.Stop() | Prevents the Timer from firing; false if it already fired or was stopped |
(*Timer) Reset(d Duration) bool timer.Reset(time.Second) | Reschedules the Timer to fire after d from now |
(*Ticker) Stop() ticker.Stop() | Stops the Ticker; the underlying goroutine does not release until Stop is called |
(*Ticker) Reset(d Duration) ticker.Reset(time.Second) | Changes the Ticker's period to d |
Duration methods
| Function | Description |
|---|---|
Hours() / Minutes() / Seconds() float64 d.Seconds() | d expressed as a floating-point count of the given unit |
Milliseconds() / Microseconds() / Nanoseconds() int64 d.Milliseconds() | d expressed as an integer count of the given unit |
String() string d.String() | Formats d like "1h30m0s", the same form ParseDuration accepts |
Truncate(m Duration) Duration d.Truncate(time.Second) | Rounds d down to a multiple of m |
Round(m Duration) Duration d.Round(time.Second) | Rounds d to the nearest multiple of m, ties rounding away from zero |