Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 147 ยท Concurrency

Time, Timers and Tickers

Learn Go's time package - Duration, Time values, the 2006-01-02 layout, parsing, time zones, the monotonic clock, Sleep, Timer, Ticker, AfterFunc and how to keep time-based code testable.

Almost every real program deals with time: how long a request took, when a token expires, which day an invoice is due, how often to retry. Go keeps all of this in one package, time, built on two types: time.Duration for a length of time and time.Time for a moment. Once you know the difference between those two, and the odd-looking layout strings used for formatting, the rest of the package follows naturally.

This lesson covers durations, building and comparing moments, formatting and parsing, time zones, the monotonic clock, and the tools that make time pass inside a program: Sleep, Timer, Ticker and AfterFunc. Because the clock changes every time you run a program, the examples use fixed dates and print comparisons such as elapsed >= 50ms instead of raw readings. Never print time.Now() and expect the same output twice.

Durations

A time.Duration is an int64 that counts nanoseconds. The package defines constants for the common units, and you build durations by multiplying them:

Go Working with time.Duration

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.

Four things to remember:

  • Println uses the String method, which prints 1.5s, 2h45m0s and 350ยตs. Use %d if you really want the raw nanosecond count.
  • time.Second * 3 works because 3 is an untyped constant. With a variable, write time.Duration(n) * time.Second. Writing n * time.Second with an int variable is a compile error (a type mismatch).
  • Seconds(), Minutes() and Hours() return float64; Milliseconds() and Microseconds() return int64 whole numbers.
  • time.ParseDuration accepts ns, us, ยตs, ms, s, m and h. There is no day or week unit, because their length depends on time zones and calendars. Use AddDate for those.

The largest duration is about 292 years, which is plenty for measuring intervals but not for describing a date far away. That is the job of time.Time.

Moments in time: time.Time

A time.Time represents an instant with nanosecond precision, plus a location (time zone) used when you display it. Build one with time.Date, and take it apart with its methods:

Go Creating, comparing and shifting Time values

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.

Look closely at these results:

  • AddDate(0, 1, 0) from January 31 gives March 3, not "the last day of February". The calendar fields are added first (February 31) and then normalized (February has 28 days in 2026, so day 31 spills over into March 3). Be careful when adding months to dates near the end of a month.
  • time.Date(2026, 14, 35, 25, 61, 0, 0, time.UTC) is accepted and normalized to 2027-03-08 02:01:00, because month 14 is February of the next year and so on. Normalization is handy for date arithmetic and dangerous for input validation. Never use it to check user input.
  • The zero value of Time is January 1 of year 1 (UTC), not 1970. Test for it with IsZero(), never by comparing to 0.
  • Compare moments with Before, After, Equal or Compare (returns -1, 0 or +1). Do not use == on Time values: it also compares the location and the monotonic reading (explained below), so two values for the same instant can be unequal.

Time is a small value type. Pass and store it by value, not by pointer. It is safe to copy, and to use from many goroutines as long as no one modifies the variable that holds it.

Formatting and parsing with layouts

Most languages use letters like YYYY-MM-DD to describe a date format. Go uses an example instead. You write how the specific reference moment

TEXT
Mon Jan 2 15:04:05 MST 2006

would look in your format, and Go substitutes the real values. The numbers are 1 to 7 in order (month 1, day 2, hour 15 or 3, minute 04, second 05, year 06 or 2006, zone -0700 which is hour 7). That is why the year in Go layouts is always 2006 and the day 02.

Go Layouts with Format

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.

The most useful pieces are:

Part Meaning Example
2006 / 06 year 2026 / 26
01 / 1 / Jan / January month 07 / 7 / Jul / July
02 / 2 / _2 day (zero-padded / plain / space-padded) 04 / 4 / 4
15 / 03 / 3 + PM hour (24-hour / 12-hour padded / plain) 09 / 09 / 9
04, 05 minute, second 05, 03
.000 / .999 fraction of a second (fixed width / trailing zeros dropped) .120 / .12
Mon / Monday weekday Sat / Saturday
MST / -0700 / Z07:00 zone name / offset / offset or Z for UTC UTC / +0000 / Z

You rarely need to type a layout. The package has constants for the standard ones: time.RFC3339 is the format for APIs and JSON (2026-07-04T09:05:03Z), and time.DateTime, time.DateOnly and time.TimeOnly (added in Go 1.20) cover the everyday database-style formats.

Parsing

time.Parse(layout, text) goes the other way. It returns an error when the text does not match the layout, or when a field is out of range:

Go Parsing dates and handling errors

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.

Unlike time.Date, Parse validates: 2026-02-30 is rejected with day out of range. If the text carries no zone information, Parse assumes UTC. When you want another zone, use time.ParseInLocation, shown in the next section.

Time zones

A Time always has a *time.Location. The same instant can be displayed in any zone with In, and the instant itself does not change. Three sources of locations:

  • time.UTC: Coordinated Universal Time. Store and compare times in UTC.
  • time.FixedZone(name, offsetSeconds): a constant offset with no daylight saving rules.
  • time.LoadLocation("America/New_York"): a zone from the IANA database, with daylight saving changes.
Go Converting between zones

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.

New York is EST (UTC-5) in January and EDT (UTC-4) in July, and In picks the right offset for each instant. LoadLocation reads the zone database from the operating system. On a minimal server or container that has no zone data it fails, so either install the data or add import _ "time/tzdata" to your program, which embeds a copy at the cost of roughly 450 KB.

Store and transmit times as UTC (or as Unix timestamps), and convert to a local zone only when showing them to a person. Keep the user's zone name (like Europe/Berlin) when you need future wall-clock times such as "every Monday at 9:00", because the offset of that zone can change with daylight saving.

Waiting: Sleep, After and Timer

time.Sleep(d) pauses the current goroutine for at least d. Other goroutines keep running. It is fine for demos and simple retry delays, but it is the wrong tool for synchronizing goroutines (see data races for why).

A time.Timer fires once, after a delay. It has a channel C that receives the time when the timer expires. You use it in a select or receive from it directly:

Go Timer, Stop, Reset and AfterFunc

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.

Stop returns true if it prevented the timer from firing, and false if the timer had already fired or been stopped. Since Go 1.23, Stop and Reset also guarantee that no stale value from the old timer is delivered afterwards, so the old advice to "drain the channel after Stop" is no longer needed on a modern go.mod. Another 1.23 change: timers that nobody references anymore are garbage collected even if they were never stopped.

time.After(d) is a shortcut that returns the channel of a new timer. It is perfect for a one-off timeout inside a select:

Go
select {
case res := <-results:
	fmt.Println("got", res)
case <-time.After(2 * time.Second):
	fmt.Println("timed out")
}

For timeouts that must also cancel the work, and propagate through several function calls, prefer the context package. The select patterns are explored further in buffered channels and select.

Repeating: Ticker

A time.Ticker sends on its channel at regular intervals until you stop it. Always call Stop (usually with defer) when you are done, otherwise the ticker keeps running and its resources are not released promptly.

Go A ticker with a deadline

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.

A ticker does not queue up missed ticks. If your loop is busy for five periods, you do not get five ticks in a row; the ticker drops the ones nobody received. That keeps a slow consumer from building a backlog, but it also means a ticker is not an exact counter of elapsed time. Count with time.Since(start) when you need accuracy. Ticker.Reset(d) changes the period of a running ticker. For a ticker that lives for the whole program, time.Tick(d) returns just the channel, and since Go 1.23 it is also garbage collected when unused.

Measuring time and the monotonic clock

To measure how long something took, take a start time and use time.Since:

Go Measuring elapsed time and the monotonic reading

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.

A wall clock can jump: a network time sync or a daylight saving change can move it backwards in the middle of your measurement. To make Since and Sub safe, every value returned by time.Now() also carries a monotonic clock reading, a counter that only goes forward. When both values have one, Sub, Since and Until use the monotonic readings and ignore wall-clock jumps. The reading is stripped by Round(0), Truncate, AddDate, In, UTC and Local, and it is never encoded into text such as JSON or Format output. It is also the reason a == b is false above while a.Equal(b) is true.

Parse errors, zones and text encodings

Two details of parsing trip up almost everyone. First, time.Parse without a zone in the text assumes UTC, not your local zone. When the text has no offset but you know which zone it was written in, use time.ParseInLocation. Second, a failed parse returns a *time.ParseError, which tells you exactly which part of the layout did not match:

Go ParseInLocation and ParseError

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.

Parse reads the text as UTC, so the two results differ by two hours (Berlin is UTC+2 in July). The month 13 is out of range, so errors.As finds the *time.ParseError, whose Value (the whole text), LayoutElem (01, the month part of the layout) and Message (: month out of range) fields name the failing piece.

Unix timestamps, YearDay and JSON

Beyond Unix() and UnixMilli() there is UnixNano(), which returns nanoseconds since January 1, 1970 UTC (an int64 that overflows in the year 2262, so do not use it for far-future dates). To go back, use time.Unix(sec, nsec), time.UnixMilli or time.UnixMicro. YearDay() gives 1 to 365 (366 in leap years).

A time.Time also knows how to encode itself. It implements MarshalJSON, UnmarshalJSON, MarshalText and UnmarshalText using the RFC 3339 format, which is why it just works inside a struct passed to encoding/json:

Go Time in JSON and as Unix nanoseconds

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.

The JSON holds 2026-03-01T08:15:00.0000005Z: trailing zeros of the fraction are dropped, but the nanoseconds survive the round trip. A date in any other format, such as 01/03/2026, is rejected with an error. If your API uses a different format, wrap time.Time in your own type and implement UnmarshalJSON with time.Parse and your layout.

Writing code that tests well

Code that calls time.Now() directly is hard to test, because the result depends on when the test runs. A common fix is to inject the clock: pass a function (or a small interface) that returns the current time, and use the real one only in main:

Go Injecting a clock for deterministic code

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.

Every result is exact, and no test ever has to wait. For code that really uses timers and sleeps, Go 1.25 added the testing/synctest package, which runs goroutines in a bubble with a fake clock where sleeping jumps forward instantly. It is covered in testing concurrent code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fmt.Println(90 * time.Second) print?

    Duration's String method breaks the value into hours, minutes and seconds, so 90 seconds prints as 1m30s.
  2. 2. What is the zero value of time.Time?

    The zero Time is year 1, January 1, 00:00:00 UTC. Use IsZero() to test for it. 1970 is the Unix epoch, which is a different thing.
  3. 3. Which layout string produces output like 2026-07-04?

    Go layouts are written by showing the reference time Mon Jan 2 15:04:05 MST 2006. The year is 2006, the month 01 and the day 02. time.DateOnly is the same string.
  4. 4. A program computes time.Date(2026, 1, 31, 0, 0, 0, 0, time.UTC).AddDate(0, 1, 0). What date does it get?

    AddDate adds the month first (February 31) and then normalizes. February 2026 has 28 days, so the extra 3 days roll over to March 3.
  5. 5. Why should you call ticker.Stop() (for example with defer) when you are finished with a ticker?

    A running ticker keeps producing ticks until stopped. Stopping it releases its resources promptly.

Summary

  • time.Duration is a length of time (an int64 of nanoseconds) built from constants like time.Second; time.Time is a moment with a location. A variable count needs time.Duration(n) * time.Second.
  • Create moments with time.Date, shift them with Add (a Duration) or AddDate (calendar fields, which normalize), compare with Before, After, Equal or Compare, and never use ==.
  • Layouts are written with the reference time Mon Jan 2 15:04:05 MST 2006. Use the constants time.RFC3339, time.DateTime, time.DateOnly and time.TimeOnly where you can; time.Parse validates its input.
  • Store times in UTC, convert with In, and use LoadLocation (or time/tzdata) for named zones with daylight saving.
  • Sleep pauses one goroutine, Timer fires once, Ticker fires repeatedly (always Stop it) and AfterFunc runs a function later. Since Go 1.23, Stop and Reset never leave stale values behind.
  • time.Now() carries a monotonic reading so Since and Sub are immune to clock changes.
  • Inject a clock function to keep time-dependent code deterministic.

Next: Testing Concurrent Code shows how to test goroutines, timers and channels without flaky sleeps.