How to validate a date in Golang?

Member

by samara , in category: Golang , a year ago

How to validate a date in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by lewis_collier , a year ago

@samara To validate a date in Golang, you can use the time.Parse function from the time package. The function takes a date string and a format string, and it returns a time.Time value representing the parsed date, along with a nil error value if the date is valid. Here's an example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
   "fmt"
   "time"
)

func main() {
   // Define the date string and format
   dateStr := "2022-12-15"
   format := "2006-01-02"

   // Parse the date using the given format
   parsedDate, err := time.Parse(format, dateStr)
   if err != nil {
      // Handle the error
      fmt.Printf("Error parsing date: %s\n", err)
      return
   }

   // Output:
   // Parsed date: 2022-12-15 00:00:00 +0000 UTC
   fmt.Printf("Parsed date: %s\n", parsedDate)
}


Note that the time.Parse function is strict about the format of the date string. If the date string does not exactly match the format specified in the format string, the time.Parse function will return an error. You should always check the error value returned by the time.Parse function to make sure the date was parsed successfully.

Member

by marina , 5 months ago

@samara 

In addition to the answer provided above, if you want to validate a date instead of parsing it, you can use the time.Parse function along with the time.IsValid method introduced in Go 1.15. The IsValid method checks if a given date is a valid date according to the Gregorian calendar. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
	"fmt"
	"time"
)

func main() {
	// Define the date string and format
	dateStr := "2022-12-15"
	format := "2006-01-02"

	// Parse the date using the given format
	parsedDate, err := time.Parse(format, dateStr)
	if err != nil {
		// Handle the error
		fmt.Printf("Error parsing date: %s
", err)
		return
	}

	// Check if the date is valid
	if !parsedDate.IsValid() {
		fmt.Println("Invalid date")
		return
	}

	// Output:
	// Parsed and valid date: 2022-12-15 00:00:00 +0000 UTC
	fmt.Printf("Parsed and valid date: %s
", parsedDate)
}


In the code snippet above, the IsValid method is called on the time.Time value parsedDate to check if it represents a valid date. If the date is valid, it will be printed; otherwise, an "Invalid date" message will be displayed.