Answer the question
In order to leave comments, you need to log in
Golang: package time. Is it possible to regularly check the date for correctness?
Good day!
package main
import (
"fmt"
"time"
)
func Check(format, date string) bool {
_, err := time.Parse(format, date)
if err != nil {
return false
}
return true
}
func main() {
fmt.Println(Check("02.01.2006", "29.02.2015")) // true
fmt.Println(Check("02.01.2006", "30.02.2016")) // true
fmt.Println(Check("02.01.2006", "31.04.2015")) // true
fmt.Println(Check("02.01.2006", "32.04.2015")) // false
}
var nonLeapYear = []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
var leapYear = []int{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
func Check(format string, date string) bool {
t, err := time.Parse(format, date)
if err != nil {
return false
}
y, m, d := t.Year(), t.Month(), t.Day()
l := nonLeapYear
if y%4 == 0 && (y%100 != 0 || y%400 == 0) {
l = leapYear
}
if d > l[m-1] {
return false
}
return true
}
time.Parse
it will work fine. Operatively.The time package's Parse function has always rejected any day of month larger than 31, such as January 32. In Go 1.6, Parse now also rejects February 29 in non-leap years, February 30, February 31, April 31, June 31, September 31, and November 31.
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question