How to verify date format in GoLang?



How to verify date format in GoLang?

How to verify date format in GoLang?

Learn how to verify date format in Golang.

In Go, you can use the time package to parse a string representation of a date and time, and then check if the result is a valid time.

In this example, the str variable contains the date and time string that we want to parse, and the layout variable defines the format of the string (used as a reference of what the date and time format should be). The time.Parse function is used to parse the string into a time.Time value. If the parse is successful, the t variable will contain the parsed time, and err will be nil. If the parse is unsuccessful, the t variable will contain the zero value of time.Time, and err will contain the error message.

Here’s an example:
package main

import (
“fmt”
“time”
)

func main() {
str := “2022-11-30T00:00:00Z”
layout := “2006-01-02T15:04:05Z”
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println(“Error: Invalid date time string”)
} else {
fmt.Println(“Valid date time string:”, t)
}
}

Run it in the Go Playground from this link
https://goplay.tools/snippet/ziTCnbHnj7B

#golang #go #golangtutorial