Go Reference ยท Time, Math and Randomness
Go time package
Overview of the Go time package: Time and Duration values, Now, Date, Add, Sub, comparison, formatting layouts, time zones, timers, tickers and monotonic clocks.
The time package measures and displays time. Its two central types are time.Time, an instant with nanosecond precision and an optional time zone, and time.Duration, an amount of time stored as an int64 count of nanoseconds. Around them it offers formatting and parsing, calendar arithmetic, time zones, sleeping, timers and tickers.
Two design points matter from day one. First, Time values are meant to be passed and stored by value and compared with methods (Equal, Before, After), not with ==. Second, a Time returned by time.Now() carries a monotonic clock reading, so measuring elapsed time is immune to the system clock being adjusted.
start := time.Now() deadline := start.Add(90 * time.Minute) fmt.Println(deadline.Sub(start)) // 1h30m0s
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
The package surface, grouped:
// values type Time struct { /* unexported */ } type Duration int64 type Month int type Weekday int type Location struct { /* unexported */ } // creating times func Now() Time func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time func Unix(sec int64, nsec int64) Time func UnixMilli(msec int64) Time func Parse(layout, value string) (Time, error) func ParseInLocation(layout, value string, loc *Location) (Time, error) // durations func Since(t Time) Duration func Until(t Time) Duration func ParseDuration(s string) (Duration, error) // waiting func Sleep(d Duration) func After(d Duration) <-chan Time func Tick(d Duration) <-chan Time func NewTimer(d Duration) *Timer func NewTicker(d Duration) *Ticker func AfterFunc(d Duration, f func()) *Timer // zones func LoadLocation(name string) (*Location, error) func FixedZone(name string, offset int) *Location var UTC *Location var Local *Location
| Group | What to know |
|---|---|
| Components | Year, Month, Day, Hour, Minute, Second, Nanosecond, Weekday, YearDay, ISOWeek, Date(), Clock(). |
| Arithmetic | Add(d), Sub(t), AddDate(y, m, d), Truncate(d), Round(d). |
| Comparison | Equal, Before, After, Compare (Go 1.20), IsZero. |
| Conversion | Unix, UnixMilli, UnixMicro, UnixNano, In(loc), UTC(), Local(), Zone(). |
| Layout constants | RFC3339, RFC1123, Kitchen, DateTime, DateOnly, TimeOnly, RFC3339Nano and more. |
| Encoding | Time implements MarshalJSON, MarshalText (RFC 3339), GobEncode and MarshalBinary. |
Errors: Parse returns a *time.ParseError; LoadLocation fails when the time-zone database cannot be found (import time/tzdata to embed it).
Usage notes
- Compare with
Equal, not==.==also compares the location pointer and the monotonic reading, so two equal instants can be!=. - Use
Durationconstants (time.Second * 5), not bare integers.time.Sleep(5)sleeps five nanoseconds. - The zero
Timeis January 1, year 1, 00:00:00 UTC. Test withIsZero, never by comparing to a literal date. - Formatting uses a reference time,
Mon Jan 2 15:04:05 MST 2006, notYYYY-MM-DDcodes. See the format page. AddDatenormalizes overflowing days, and daylight-saving changes make a calendar day 23 or 25 hours long;Add(24*time.Hour)andAddDate(0, 0, 1)therefore differ across such a change.- Store and transmit UTC (or RFC 3339 strings with offset) and convert to a zone only for display.
- Time zone data:
LoadLocation("Europe/Berlin")needs the host's tz database;import _ "time/tzdata"adds about 450 KB to the binary but works everywhere. - Monotonic readings are stripped by
Round(0),UTC(),In,Truncateand by encoding; uset.Round(0)before storing aTimeyou want to compare with==. - Tickers and timers hold resources; stop them (
Stop) when done. Since Go 1.23 timers that are no longer referenced are garbage-collected even if not stopped, andReset/Stopnever leave a stale value in the channel. - Testing: inject a
func() time.Timeor a clock interface instead of callingtime.Now()deep in your code (Go 1.25'stesting/synctestcan also fake the clock for concurrent code).