go · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
The time toolbox builds dates, formats them and does sums.
time.Date(2026, time.March, 14, 18, 30, 0, 0, time.UTC) builds a : year, month, day, hour, minute, second, a tiny fraction of a second, then the time zone. A fixed date like this gives the same answer on every run.
To show a date, hand Format a written with Go's reference date, Monday 2 January 2006 at 15:04. party.Format("Mon 2 Jan 2006") gives Sat 14 Mar 2026. Move the pieces around for any style you like.
party.AddDate(0, 0, 7) adds years, months and days. later.Sub(party) gives a , and Hours() turns it into a number of hours. Before and After compare two moments, and Weekday names the day.
package main
import "fmt"
import "time"
func main() {
party := time.Date(2026, time.March, 14, 18, 30, 0, 0, time.UTC)
fmt.Println(party.Format("Mon 2 Jan 2006 at 15:04"))
nextWeek := party.AddDate(0, 0, 7)
fmt.Println(nextWeek.Format("2 January"), nextWeek.Weekday())
gap := nextWeek.Sub(party)
fmt.Println(gap, gap.Hours()/24, "days")
fmt.Println(party.Before(nextWeek))
} Every layout uses those exact reference numbers, so 01 means the month and 02 means the day.
guess first
Three days after 30 December. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
import "time"
func main() {
start := time.Date(2026, time.December, 30, 0, 0, 0, 0, time.UTC)
end := start.AddDate(0, 0, 3)
fmt.Println(end.Format("2 Jan 2006"))
}
your turn
Your turn. Which day were you born?
Type a birthday, yours or anyone's: the year, the month's English name with a capital letter, and the day. Go works out the weekday for you.
output
press run to see what happens
fix it
The library due date is scrambled. Fix it!
output
press run to see what happens
- The year looks very odd. A layout must use Go's reference date exactly.
- The reference year is 2006, but the layout on line 7 says 2026.
- Change "02/01/2026" to "02/01/2006" on line 7, then run.
nailed it
you can count the days now. :D
time.Datebuilds a fixed moment that is the same every run.- Layouts use the reference date: Mon 2 Jan 2006 15:04.
AddDatemoves a date, andSubmeasures the gap.
new words in your collection
- time.Time
- layout
- Duration
This lesson isn’t saved. A free account remembers every lesson you finish.