M
M
memba2015-12-08 14:34:36
go
memba, 2015-12-08 14:34:36

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
}

Of course, dealing with dates and times is not an easy thing to do in a language. How other languages ​​do it... Well, the Duration type of the time package only works with hours at most... But not to take into account 30/31 days in a month and a leap year...
I don't see a regular way to check the date for correctness. Add functionality or are there any ready-made libraries?
Update
Could be done like this:
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
}

But for February 29-31 or April 31, Go says that t.Month() is March (3) and May (5) respectively.
So it is not possible to use regular Parse. And I don’t really want to write the same one of my own.
Update #2
Today (12/18/15) we announced the release of Go 1.6 beta 1. Now time.Parseit 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 question

Ask a Question

731 491 924 answers to any question