Add support for mm/dd/yyyy, hh:mm:ss

Incorporate PR https://github.com/araddon/dateparse/pull/156 from https://github.com/BrianLeishman and adapt to also validate the format
This commit is contained in:
Klondike Dragon 2023-12-14 23:14:26 -07:00
parent 14fb9398e4
commit 23869f345e
2 changed files with 14 additions and 5 deletions

View File

@ -254,14 +254,14 @@ func parseTime(datestr string, loc *time.Location, opts ...ParserOption) (p *par
if p != nil && p.ambiguousMD {
// if it errors out with the following error, swap before we
// get out of this function to reduce scope it needs to be applied on
_, err := p.parse()
_, err = p.parse()
if err != nil && strings.Contains(err.Error(), "month out of range") {
// create the option to reverse the preference
preferMonthFirst := PreferMonthFirst(!p.preferMonthFirst)
// turn off the retry to avoid endless recursion
retryAmbiguousDateWithSwap := RetryAmbiguousDateWithSwap(false)
modifiedOpts := append(opts, preferMonthFirst, retryAmbiguousDateWithSwap)
p, _ = parseTime(datestr, time.Local, modifiedOpts...)
p, err = parseTime(datestr, time.Local, modifiedOpts...)
}
}
@ -684,6 +684,7 @@ iterRunes:
case dateDigitSlash:
// 03/19/2012 10:11:59
// 04/2/2014 03:00:37
// 04/2/2014, 03:00:37
// 3/1/2012 10:11:59
// 4/8/2014 22:05
// 3/1/2014
@ -713,10 +714,14 @@ iterRunes:
}
// Note no break, we are going to pass by and re-enter this dateDigitSlash
// and look for ending (space) or not (just date)
case ' ':
case ' ', ',':
p.stateTime = timeStart
if p.yearlen == 0 {
p.yearlen = i - p.yeari
if r == ',' {
// skip the comma
i++
}
if !p.setYear() {
return p, unknownErr(datestr)
}

View File

@ -9,8 +9,7 @@ import (
)
func TestOne(t *testing.T) {
time.Local = time.UTC
var ts = MustParse("2020-07-20+08:00")
ts := MustParse("2020-07-20+08:00")
assert.Equal(t, "2020-07-19 16:00:00 +0000 UTC", fmt.Sprintf("%v", ts.In(time.UTC)))
}
@ -431,6 +430,11 @@ var testInputs = []dateTest{
{in: "Jul 9, 2012 at 5:02am (EST)", out: "2012-07-09 05:02:00 +0000 UTC", zname: "EST"},
{in: "Jul 9, 2012 at 5:02am (EST)", out: "2012-07-09 05:02:00 +0000 UTC", loc: "US/Pacific", zname: "EST"},
{in: "Jul 9, 2012 at 5:02am (EST)", out: "2012-07-09 10:02:00 +0000 UTC", loc: "America/New_York", zname: "EDT"},
// https://github.com/araddon/dateparse/pull/156
{in: "04/02/2014, 04:08:09", out: "2014-04-02 04:08:09 +0000 UTC"},
{in: "4/2/2014, 04:08:09", out: "2014-04-02 04:08:09 +0000 UTC"},
{in: "04/02/2014, 04:08 AM", out: "2014-04-02 04:08:00 +0000 UTC"},
{in: "04/02/2014, 04:08 PM", out: "2014-04-02 16:08:00 +0000 UTC"},
// yyyy-mm-dd hh:mm:ss,000
{in: "2014-05-11 08:20:13,787", out: "2014-05-11 08:20:13.787 +0000 UTC"},
// yyyy-mm-dd hh:mm:ss +0000