Go time.Parse error
Parse returns an error if an ISO date contains an impossible day.
A simple example
time.Parse error
- Start with 2024-02-30
- Do this Validate the date
- Result Invalid date
Syntax
time.Parse(time.DateOnly, text)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goCheck a delivery date entered on a form
A grocery customer chooses February 30 as a delivery date. The booking desk needs to reject the impossible date and let the customer pick another day before a driver is scheduled.
ResultChoose a valid date
package main
import (
"fmt"
"time"
)
func main() {
date, err := time.Parse(time.DateOnly, "2025-02-30")
if err != nil {
fmt.Println("Choose a valid date")
} else {
fmt.Println(date.Format(time.DateOnly))
}
}
Choose a valid date
February 30 cannot be booked even though the input uses the expected year-month-day format.
Advertisements
Accept a leap-year rehearsal
The music room receives a booking request for the leap day in 2028. Validate the submitted ISO date before adding the booking to the schedule.
Given2028-02-29
Worked resultBooking date accepted
Reject a short-month overflow
A tutor tries to book the art room for the thirty-first day of April. Validate the submitted ISO date before adding the booking to the schedule.
Given2027-04-31
Worked resultAsk for a new date
What to watch for
Check the error before using the returned Time.