How to Validate date in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to Validate date using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
In this program I have replaced the angled brackets with > or <. once you copy the source code to editor replace it with greater than or less than symbols respectively.
##############SOURCE CODE#########################
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
var date string
fmt.Print("Enter date in format (dd-mm-yyyy): ")
fmt.Scan(&date)
parts := strings.Split(date, "-")
if len(parts) != 3 {
fmt.Println("Invalid date format")
return
}
day, err := strconv.Atoi(parts[0])
if err != nil {
fmt.Println("Invalid day")
return
}
month, err := strconv.Atoi(parts[1])
if err != nil {
fmt.Println("Invalid month")
return
}
year, err := strconv.Atoi(parts[2])
if err != nil {
fmt.Println("Invalid year")
return
}
if year < 0 || year > 9999 {
fmt.Println("Invalid year")
return
}
if month < 1 || month > 12 {
fmt.Println("Invalid month")
return
}
if day < 1 || day > daysInMonth(month, year) {
fmt.Println("Invalid day")
return
}
fmt.Println("Valid date")
}
func daysInMonth(month, year int) int {
if month == 2 {
if isLeapYear(year) {
return 29
}
return 28
}
if month == 4 || month == 6 || month == 9 || month == 11 {
return 30
}
return 31
}
func isLeapYear(year int) bool {
if year%4 == 0 && (year%100 != 0 || year%400 == 0) {
return true
}
return false
}
Below is the explanation for the program:
In this program, we prompt the user to enter a date in the format dd-mm-yyyy, and then use string manipulation to extract the day, month, and year components of the date.
We then convert these components to integers and validate them to ensure that they are within the appropriate ranges for a valid date.
We first check that the year is between 0 and 9999, inclusive. We then check that the month is between 1 and 12, inclusive.
Finally, we use a daysInMonth function to determine the number of days in the given month, and check that the day component of the date is between 1 and the number of days in the month.
If any of these checks fail, we print an error message and return from the function.
Otherwise, we print a message indicating that the date is valid.
Note that this implementation does not check for edge cases such as the year 0, or dates before the adoption of the Gregorian calendar
#go #goprogramming #golang #golangtutorial #golanguage