Go time.Parse and Time.AddDate
time.Parse reads a date with Go's reference layout. AddDate advances calendar years, months, and days.
A simple example
time.Parse and Time.AddDate
- Start with 2024-01-31
- Do this Add one calendar day
- Result 2024-02-01
Syntax
day, err := time.Parse("2006-01-02", text)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Cross a leap day using a calendar date
A reporting or booking deadline falls close to the end of a month. Use a calendar operation and validate the input so a leap day or an invalid date cannot silently shift the deadline.
package main
import (
"fmt"
"time"
)
func main() {
for _, text := range []string{"2024-02-29", "2023-02-29"} {
day, err := time.Parse("2006-01-02", text)
if err != nil {
fmt.Println("invalid date")
continue
}
fmt.Println(day.AddDate(0, 0, 1).Format("2006-01-02"))
}
}
2024-03-01 invalid date
The layout uses example digits from Go's reference date. Parsing rejects an impossible February 29, while adding one day to a valid leap day reaches March 1.
Go documentation for time.Parse and Time.AddDate
Return a borrowed microscope
A school lends a microscope two days before the end of February in a leap year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?
Send a year-end reminder
A gallery schedules its reminder one day after the final day of the year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?