Skip to content

Commit

Permalink
Tweak date parsing again
Browse files Browse the repository at this point in the history
  • Loading branch information
rowanseymour committed May 24, 2024
1 parent 2cd3dba commit a5603f1
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions envs/dates.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,22 +71,13 @@ var isoFormats = []string{iso8601Format, iso8601NoSecondsFormat}
var ZeroDateTime = time.Time{}

func dateFromFormats(currentYear int, pattern *regexp.Regexp, d int, m int, y int, str string) (dates.Date, string, error) {

matches := pattern.FindAllStringSubmatchIndex(str, -1)
for _, match := range matches {
groups := utils.StringSlices(str, match)

// does our day look believable?
day, _ := strconv.Atoi(groups[d])
if day == 0 || day > 31 {
continue
}
month, _ := strconv.Atoi(groups[m])
if month == 0 || month > 12 {
continue
}

year, _ := strconv.Atoi(groups[y])
month, _ := strconv.Atoi(groups[m])
day, _ := strconv.Atoi(groups[d])

// convert to four digit year if necessary
if len(groups[y]) == 2 {
Expand All @@ -97,13 +88,22 @@ func dateFromFormats(currentYear int, pattern *regexp.Regexp, d int, m int, y in
}
}

remainder := str[match[1]:]
// does our day and month look believable?
if day == 0 || day > 31 {
continue
}
if month == 0 || month > 12 {
continue
}

_, err := time.Parse("2006-01-02", fmt.Sprintf("%d-%02d-%02d", year, month, day))
// lean time.Parse to check if the year, month and day values are valid together, i.e. no 30 of Feb
_, err := time.Parse("2006-1-2", fmt.Sprintf("%d-%d-%d", year, month, day))
if err != nil {
return dates.ZeroDate, str, fmt.Errorf("string '%s' couldn't be parsed as a date", str)
continue
}

remainder := str[match[1]:]

// looks believable, go for it
return dates.NewDate(year, month, day), remainder, nil
}
Expand Down

0 comments on commit a5603f1

Please sign in to comment.