35. Time and dates

A to-do list should remember when each task was added. A reminder needs to know how long to wait. A report wants today's date at the top. All of these need the time package, the last tool before the Part 7 mini-project.

This chapter shows how to get the current time, make dates of your own, turn them into text and back, work with amounts of time, add to dates and count the days between them, wait and measure, and test code that depends on the clock.

The time now

time.Now() returns the current date and time, as a value of the type time.Time. This is exercises/35/01-now.go, inside main:

now := time.Now()
fmt.Println(now)

fmt.Println("Year:   ", now.Year())
fmt.Println("Month:  ", now.Month())
fmt.Println("Day:    ", now.Day())
fmt.Println("Weekday:", now.Weekday())
fmt.Printf("Time:    %02d:%02d\n", now.Hour(), now.Minute())

The output depends on when you run it. On a Sunday afternoon in August 2025, in Jakarta, it printed:

2025-08-17 14:05:09.4515339 +0700 +07 m=+0.000519801
Year:    2025
Month:   August
Day:     17
Weekday: Sunday
Time:    14:05

The first line is the whole value: the date, the time down to a tiny part of a second, and the time zone, here 7 hours ahead of UTC. The zone's name at the end depends on your computer's settings. The m= part is something Go keeps for measuring time, shown later in this chapter. You never need to read it.

A time.Time has a method for each part: Year, Month, Day, Hour, Minute, Second and Weekday. Year, Day, Hour and Minute give an int. Month and Weekday give their own types, time.Month and time.Weekday, which print as a name. %02d is the %5d from Chapter 14 with a 0 in front: it pads the number to two digits with zeros instead of spaces, so 9:05 prints as 09:05.

A date of your own

Most dates in a program are not "now": a birthday, a due date, the date in a file. time.Date makes one from its parts. This is exercises/35/02-date.go, inside main:

start := time.Date(2025, time.August, 17, 9, 30, 0, 0, time.UTC)
fmt.Println(start)
fmt.Println(start.Year(), start.Month(), start.Day())
fmt.Println(start.Weekday())

// Go moves values that are too big into the next month.
odd := time.Date(2025, time.January, 32, 0, 0, 0, 0, time.UTC)
fmt.Println(odd.Month(), odd.Day())

// time.Local is the time zone of your computer.
meeting := time.Date(2025, time.August, 18, 14, 0, 0, 0, time.Local)
fmt.Println(meeting.Hour(), meeting.Minute())

Output:

2025-08-17 09:30:00 +0000 UTC
2025 August 17
Sunday
February 1
14 0

time.Date takes eight values, always in this order: year, month, day, hour, minute, second, nanosecond (a billionth of a second, almost always 0), and the time zone. Months are constants, time.January to time.December, so you cannot mix up the month and the day.

The time zone is called a location:

  • time.UTC is the world's reference time, the same everywhere. Use it for dates where the clock does not matter, such as "the day a task was added".
  • time.Local is the time zone your computer is set to. Use it for times a person reads off a clock, like a meeting at 14:00.

Go does not refuse a day that is too big. January 32 becomes February 1, as if you had counted on past the end of the month. That is handy for date math, as you will see, but it also means time.Date never tells you that a date was wrong. To check a date that a user typed, use time.Parse, below.

Turning a time into text

Format turns a time into a string. You tell it the shape you want with a layout: an example of how one particular date should look. That date is always the same: Monday, January 2, 2006, at 15:04:05. This is exercises/35/03-format.go, inside main:

t := time.Date(2025, time.August, 17, 14, 5, 9, 0, time.UTC)

fmt.Println(t.Format("2006-01-02"))
fmt.Println(t.Format("02/01/2006"))
fmt.Println(t.Format("15:04"))
fmt.Println(t.Format("3:04 PM"))
fmt.Println(t.Format("2006-01-02 15:04:05"))
fmt.Println(t.Format("Monday, 2 January 2006"))
fmt.Println(t.Format("Mon 2 Jan"))

// A common mistake: letters are not a layout.
fmt.Println(t.Format("YYYY-MM-DD"))

Output:

2025-08-17
17/08/2025
14:05
2:05 PM
2025-08-17 14:05:09
Sunday, 17 August 2025
Sun 17 Aug
YYYY-MM-DD

Format looks for the parts of the reference date in your layout and puts the same part of your time in their place. Everything else, such as -, /, , and spaces, is copied as it is. The parts it knows:

In the layout Means For 2025-08-17 14:05:09
2006 year 2025
01 month, two digits 08
Jan / January month name Aug / August
02 day, two digits 17
2 day 17
Mon / Monday weekday name Sun / Sunday
15 hour, 0 to 23 14
3 / 03 hour, 1 to 12 2 / 02
04 minute 05
05 second 09
PM AM or PM PM

To remember the reference date, write it the American way, month first: 01/02 03:04:05PM '06. The numbers count 1, 2, 3, 4, 5, 6.

The last line of the output shows the most common mistake. YYYY-MM-DD is how many other languages write a layout, but Go does not know those letters, so it copies them unchanged. If a date comes out looking strange, check the layout against the table.

Add a line to exercises/35/03-format.go that prints the time as 17 Aug 2025, 2:05 PM.

Turning text into a time

time.Parse is the other direction. It takes a layout, written the same way, and a string, and returns a time.Time and an error. This is exercises/35/04-parse.go, inside main:

day, err := time.Parse("2006-01-02", "2025-08-17")
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println(day)
fmt.Println(day.Weekday())

clock, err := time.Parse("15:04", "07:45")
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println(clock.Hour(), clock.Minute())

// Text that does not match the layout gives an error.
_, err = time.Parse("2006-01-02", "17-08-2025")
fmt.Println("Error:", err)

_, err = time.Parse("2006-01-02", "2025-02-30")
fmt.Println("Error:", err)

Output:

2025-08-17 00:00:00 +0000 UTC
Sunday
7 45
Error: parsing time "17-08-2025" as "2006-01-02": cannot parse "17-08-2025" as "2006"
Error: parsing time "2025-02-30": day out of range
  • A part missing from the layout gets its zero: no clock means midnight. With no time zone in the text, the result is in UTC.
  • Text in another shape is refused. Go expected four digits of year at the start, and found 17-0.
  • Unlike time.Date, time.Parse checks the date. February has no 30th, so it gives an error instead of moving on to March.

This makes time.Parse the right way to read a date that a user typed, or that was stored in a file. Like strconv.Atoi, its error is meant for programmers. For a user, wrap it in a message that shows the shape you expect, such as "17-08-2025" is not a date like 2025-08-17.

Amounts of time

A time.Time is a moment. An amount of time, such as "90 minutes", is a time.Duration. The time package has constants for the units: time.Nanosecond, time.Millisecond, time.Second, time.Minute and time.Hour. Multiply them to get the amount you want. This is exercises/35/05-durations.go, inside main:

fmt.Println(90 * time.Minute)
fmt.Println(1500 * time.Millisecond)

d := 2*time.Hour + 15*time.Minute
fmt.Println(d)
fmt.Println(d.Minutes())
fmt.Println(d.Hours())

// A number in a variable must be turned into a Duration first.
minutes := 45
wait := time.Duration(minutes) * time.Minute
fmt.Println(wait)

// ParseDuration reads text such as "1h20m" or "90s".
parsed, err := time.ParseDuration("1h20m")
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println(parsed, parsed.Minutes())

_, err = time.ParseDuration("20 minutes")
fmt.Println("Error:", err)

Output:

1h30m0s
1.5s
2h15m0s
135
2.25
45m0s
1h20m0s 80
Error: time: unknown unit " minutes" in duration "20 minutes"
  • A duration prints in a short form: h, m and s, and ms for milliseconds.
  • Minutes() and Hours() give the amount as a float64, so 2h15m is 2.25 hours.
  • A time.Duration is a whole number underneath, a count of nanoseconds. 90 * time.Minute works because 90 is a constant, which Go fits to any number type. minutes is an int variable, and Go does not mix number types, as Chapter 13 showed. So turn it into a duration first: time.Duration(minutes) * time.Minute.
  • time.ParseDuration reads the short form back. It knows h, m, s and ms, but no spaces or whole words.

Date math

Moments and amounts work together. This is exercises/35/06-date-math.go:

const layout = "2006-01-02 15:04"

func main() {
    start := time.Date(2025, time.August, 17, 9, 30, 0, 0, time.UTC)

    end := start.Add(90 * time.Minute)
    fmt.Println("Ends:      ", end.Format(layout))
    fmt.Println("Length:    ", end.Sub(start))
    fmt.Println("Before:    ", start.Add(-15*time.Minute).Format(layout))

    fmt.Println("Next week: ", start.AddDate(0, 0, 7).Format(layout))
    fmt.Println("Next month:", start.AddDate(0, 1, 0).Format(layout))
    fmt.Println("Yesterday: ", start.AddDate(0, 0, -1).Format(layout))

    newYear := time.Date(2026, time.January, 1, 9, 30, 0, 0, time.UTC)
    days := int(newYear.Sub(start).Hours() / 24)
    fmt.Println("Days to new year:", days)

    fmt.Println(start.Before(end))
    fmt.Println(start.After(end))
    fmt.Println(end.Equal(start.Add(time.Hour + 30*time.Minute)))
}

Output:

Ends:       2025-08-17 11:00
Length:     1h30m0s
Before:     2025-08-17 09:15
Next week:  2025-08-24 09:30
Next month: 2025-09-17 09:30
Yesterday:  2025-08-16 09:30
Days to new year: 137
true
false
true

The methods, two by two:

  • Add moves a time by a duration: a moment plus an amount is a moment. A negative duration moves it back.
  • Sub is the other way round: one moment minus another is the amount between them, a time.Duration.
  • AddDate(years, months, days) moves by calendar steps. It keeps the clock time, and uses the same moving-on as time.Date. One month after January 31 is "February 31", which becomes early March, so be careful with months near the end.
  • Before, After and Equal compare two moments, and return a bool.

There is no method that counts days. Sub gives the duration, Hours() turns it into hours, and dividing by 24 gives days. int(...) drops the part after the point, so "136 days and 23 hours" counts as 136.

Compare times with Equal, not ==. A time.Time holds more than the moment: its location, and for time.Now, that m= reading. 16:30 in Jakarta and 09:30 UTC on the same day are the same moment, and Equal says true, but == says they differ. The mini-project's tests compare dates with Equal for this reason.

Two more things matter when you count days:

  • Use UTC. A day in UTC is always 24 hours. In countries that move their clocks for summer, one local day a year has 23 hours and one has 25, and dividing by 24 can be one off. Indonesia does not move its clocks, but your users' computers might be elsewhere.
  • Count calendar days, not hours. 23:00 today and 01:00 tomorrow are only 2 hours apart, so dividing gives 0 days, yet the second one is tomorrow. When a calendar day is what you mean, first make a copy of each time at midnight UTC on its own date: time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC). Then subtract.

Weekdays

Weekday() gives a time.Weekday, which can be compared with the constants time.Sunday to time.Saturday. This is exercises/35/07-weekdays.go:

func isWeekend(t time.Time) bool {
    day := t.Weekday()
    return day == time.Saturday || day == time.Sunday
}

func main() {
    day := time.Date(2025, time.August, 13, 0, 0, 0, 0, time.UTC)

    for range 7 {
        label := "work day"
        if isWeekend(day) {
            label = "weekend"
        }
        fmt.Printf("%s  %-9s  %s\n", day.Format("2006-01-02"), day.Weekday(), label)
        day = day.AddDate(0, 0, 1)
    }
}

Output:

2025-08-13  Wednesday  work day
2025-08-14  Thursday   work day
2025-08-15  Friday     work day
2025-08-16  Saturday   weekend
2025-08-17  Sunday     weekend
2025-08-18  Monday     work day
2025-08-19  Tuesday    work day

AddDate(0, 0, 1) steps to the next day, and the loop walks a week. %-9s pads the name to nine characters, the length of Wednesday, so the last column lines up. %s works for a weekday because it knows how to print itself as a name.

Change exercises/35/07-weekdays.go to print the whole of August 2025 and count the work days. Start on August 1, and loop while day.Month() == time.August.

Waiting

time.Sleep pauses the program for a duration. The flag package from Chapter 32 has a flag for durations, so the user can type 2s or 1m30s. This is exercises/35/08-timer.go, inside main:

wait := flag.Duration("wait", 3*time.Second, "how long to wait, such as 90s or 2m")
flag.Parse()

fmt.Printf("Waiting %v...\n", *wait)
time.Sleep(*wait)
fmt.Println("Time is up!")
go run exercises/35/08-timer.go -wait 2s
Waiting 2s...
Time is up!

The second line comes two seconds after the first. flag.Duration reads the value with time.ParseDuration, so -wait 2 seconds is refused with the same kind of help as -times abc was in Chapter 32.

Measuring

To find out how long some work takes, note the time before, and ask how much has passed after. This is exercises/35/09-measure.go. isPrime checks every possible divisor, so it is slow on purpose. main counts the primes below two million:

start := time.Now()

count := 0
for n := range 2_000_000 {
    if isPrime(n) {
        count++
    }
}

elapsed := time.Since(start)
fmt.Println("Primes below 2,000,000:", count)
fmt.Println("That took", elapsed)
fmt.Println("Rounded: ", elapsed.Round(time.Millisecond))

Output on one computer:

Primes below 2,000,000: 148933
That took 287.4519ms
Rounded:  287ms

The count is always the same. The time is different on every run, and on every computer.

  • time.Since(start) is short for time.Now().Sub(start): the duration since start. This is where the m= reading is used. It is a clock that only ever moves forward, so the measurement stays right even if the computer's clock is changed in the middle.
  • Round rounds a duration to the nearest whole unit you give it, which is easier to read.
  • 2_000_000 is two million. Go lets you put _ between digits to make long numbers readable. It changes nothing else.

Testing code that uses the clock

A function that calls time.Now() itself is hard to test: its answer changes with the time of day, so a test that passes in the morning fails in the evening. The fix is the habit from Chapter 34: take the time as a parameter. The program passes in time.Now(), and the test passes in any time it likes.

This is exercises/35/10-greeting/, a module with a package greeting. In greeting/greeting.go:

// For returns a greeting that suits the time now. It takes the time as a
// parameter, so that a test can pass in any time it likes.
func For(now time.Time) string {
    hour := now.Hour()
    switch {
    case hour < 5:
        return "Good night"
    case hour < 12:
        return "Good morning"
    case hour < 18:
        return "Good afternoon"
    default:
        return "Good evening"
    }
}

main.go is one line of work:

func main() {
    fmt.Println(greeting.For(time.Now()))
}

And greeting/greeting_test.go makes fixed times with time.Date, one per row, on both sides of every edge:

    tests := []struct {
        hour int
        want string
    }{
        {0, "Good night"},
        {4, "Good night"},
        {5, "Good morning"},
        {11, "Good morning"},
        {12, "Good afternoon"},
        {17, "Good afternoon"},
        {18, "Good evening"},
        {23, "Good evening"},
    }

    for _, tc := range tests {
        now := time.Date(2025, time.August, 17, tc.hour, 30, 0, 0, time.UTC)
        got := For(now)
        if got != tc.want {
            t.Errorf("For(%s) = %q, want %q", now.Format("15:04"), got, tc.want)
        }
    }

The rows have no names, so this test uses no t.Run. The message shows the time with Format, which is easier to read than the whole time value.

Run the program and the tests from the module's folder. The tests are in a subfolder, so use ./..., as Chapter 34 mentioned:

cd exercises/35/10-greeting
go run .
go test ./...

go run . prints a greeting for the time you run it, such as Good afternoon. go test prints one line per package:

?       greetingapp [no test files]
ok      greetingapp/greeting    0.177s

? means the main package has no tests, which is fine: it only passes the time in. The tests pass at any time of day, which is the whole point. Go back with cd ../../...

The to-do list in the mini-project works the same way. Its tasks package never calls time.Now(). main.go does, and passes the time in.

Homework

Homework starters are in exercises/35/homework/. The first three are single files that run from go-work, as usual. The challenge is a module with tests: cd into its folder.

Problem 1 — Date formats

Open exercises/35/homework/01-formats.go. Print the time t in five ways, one per line: 2025-08-17, 17/08/2025, Sunday, 17 August 2025, 14:05 and 2:05 PM. Use t.Format with a layout for each, and do not type the numbers yourself.

Problem 2 — Countdown

Open exercises/35/homework/02-countdown.go. Add a flag -from, a duration with a default of 5 seconds. Count down from it, one line per second, then print Go!. For -from 3s, it prints 3s, 2s, 1s and Go!. If -from is 0 or less, print an error to standard error and exit with code 1.

Problem 3 — Days between

Open exercises/35/homework/03-days-between.go. Take two dates from the command line, such as 2025-08-17 2025-12-25, and print the number of days between them, with their weekdays:

From Sunday 2025-08-17 to Thursday 2025-12-25: 130 days

The answer is never negative: swap the dates if the second one comes first. With the wrong number of arguments, or a date that does not parse, print a clear message to standard error and exit with code 1.

Challenge — Due label

Folder: exercises/35/homework/04-due-label/. Write Label(due, now) in due.go, which describes a due date as seen from now: due today, due tomorrow, due in 5 days, overdue by 1 day or overdue by 3 days. It counts calendar days, so the time of day does not matter. Two rows in due_test.go fail until it works. Then add rows for "due today", "overdue by 1 day", "overdue by 3 days", and a due date at 01:00 when now is 23:00 the night before.

Stuck or done? Open the homework solutions page.