Go Dates and Times
A time value holds one moment with a date and a clock time. The time package builds such moments, changes them, and writes them as text.
Build a fixed moment and format it
time.UTC names a time zone with no offset from the standard line. Date builds a moment from the parts in order, and Format writes it with the layout.
package main
import (
"fmt"
"time"
)
func main() {
moment := time.Date(2026, 10, 25, 9, 30, 0, 0, time.UTC)
fmt.Println(moment.Format("2006-01-02"))
}Add hours and days
A duration is a length of time. Add moves a moment forward by that length, and the layout 15:04 stands for the hour and the minute.
package main
import (
"fmt"
"time"
)
func main() {
moment := time.Date(2026, 10, 25, 9, 30, 0, 0, time.UTC)
later := moment.Add(2 * time.Hour)
fmt.Println(later.Format("15:04"))
next := moment.Add(48 * time.Hour)
fmt.Println(next.Format("2006-01-02"))
}Parse a date and name its weekday
Parse reads text with a layout and returns a moment. Weekday gives the day of the week of a moment.
package main
import (
"fmt"
"time"
)
func main() {
moment, err := time.Parse("2006-01-02", "2026-10-25")
if err != nil {
fmt.Println("Could not read the date")
return
}
fmt.Println(moment.Weekday())
}The duration between two moments
Sub takes the earlier moment away from the later one. The result is the duration between them.
package main
import (
"fmt"
"time"
)
func main() {
start := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
end := time.Date(2026, 10, 27, 9, 0, 0, 0, time.UTC)
fmt.Println(end.Sub(start))
}Example
package main
import (
"fmt"
"time"
)
func main() {
start := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
event := time.Date(2026, 10, 30, 9, 0, 0, 0, time.UTC)
wait := event.Sub(start)
days := int(wait.Hours() / 24)
fmt.Println("Event:", event.Format("2006-01-02"))
fmt.Println("Weekday:", event.Weekday())
fmt.Println("Days to wait:", days)
}Key points
- One time value stands for one moment.
- Use time.Date to build a moment from a year, a month, a day, and a clock time.
- A layout is a pattern for date text, written with the numbers of one sample moment.
- In a layout, 2006 stands for the year, 01 for the month, and 02 for the day.
- Use Format with a layout to turn a moment into text.
- Use time.Parse with a layout to read text into a moment.
- A duration is a length of time, and Sub gives the duration between two moments.
In this example, Date builds the start moment and the event moment. Sub gives the duration between them. Hours turns that duration into a count of hours, and the division gives 5 whole days. The prints show the event date, its weekday, and the days to wait.
Note
Every moment in this lesson is fixed, so every run prints the same output.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
Two fixed moments are 48 hours apart. What does end.Sub(start) print?