In this article, we will see how to validate a date string format in Golang.
To achieve this we use the time
package. To validate a date string format, you can use the time.Parse
function.
The time.Parse
function takes two string arguments: the layout/format and the date string to be parsed. If the date string is not formatted correctly, the function will return an error.
Following is an example of how to use the time.Parse
function:
package main
import (
"fmt"
"time"
)
func main() {
layout := "2006-01-02"
dateString := "2023-03-23"
_, err := time.Parse(layout, dateString)
if err != nil {
fmt.Println("Invalid date format:", err)
} else {
fmt.Println("Valid date format")
}
}
In the above example, we define a layout (using the format “2006-01-02“) and a date string to be validated. If the date string does not match the layout, an error will be returned and we will handle it separately in the if statement.
We can choose different formats here. In the above example, we are using the format ‘yyyy-mm-dd‘. We can also use other formats as shown below.
- RFC3339 (ISO 8601) format: “2006-01-02T15:04:05Z07:00”
- YYYY-MM-DD format: “2006-01-02”
- MM/DD/YYYY format: “01/02/2006”
- DD/MM/YYYY format: “02/01/2006”
- YYYY/MM/DD HH:mm:ss format: “2006/01/02 15:04:05”
- YYYY-MM-DDTHH:mm:ssZ (ISO 8601 without timezone offset): “2006-01-02T15:04:05Z”
- Month Day, Year: “January 2, 2006”
- Month abbreviation Day, Year: “Jan 2, 2006”
- 12-hour time format: “03:04:05 PM”
- 24-hour time format: “15:04:05”
- Unix timestamp (seconds since January 1, 1970 UTC): “%d”
- Full weekday name: “Monday”
- Short weekday name: “Mon”
- Full month name: “January”
- Short month name: “Jan”