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.

  1. RFC3339 (ISO 8601) format: “2006-01-02T15:04:05Z07:00”
  2. YYYY-MM-DD format: “2006-01-02”
  3. MM/DD/YYYY format: “01/02/2006”
  4. DD/MM/YYYY format: “02/01/2006”
  5. YYYY/MM/DD HH:mm:ss format: “2006/01/02 15:04:05”
  6. YYYY-MM-DDTHH:mm:ssZ (ISO 8601 without timezone offset): “2006-01-02T15:04:05Z”
  7. Month Day, Year: “January 2, 2006”
  8. Month abbreviation Day, Year: “Jan 2, 2006”
  9. 12-hour time format: “03:04:05 PM”
  10. 24-hour time format: “15:04:05”
  11. Unix timestamp (seconds since January 1, 1970 UTC): “%d”
  12. Full weekday name: “Monday”
  13. Short weekday name: “Mon”
  14. Full month name: “January”
  15. Short month name: “Jan”

Categorized in:

Tagged in: