spencermountain / spacetime

A lightweight javascript timezone library
http://spacetime.how/
Other
3.97k stars 185 forks source link

Invalid date string parsing #330

Closed gk061090 closed 2 years ago

gk061090 commented 2 years ago

Hi. Seems to be a bug. I entered the month incorrectly:

const testDate = spacetime('11.13.2022', 'Europe/Berlin');
testDate.isValid(); // true, but should be false
testDate.unixFmt("yyyy-MM-dd"); // "2022-11-13" - incorrect

I entered the day and month incorrectly:

const testDate = spacetime('13.13.2022', 'Europe/Berlin');
testDate.isValid(); // false - OK
testDate.unixFmt("yyyy-MM-dd"); // "1970-01-01" - OK
spencermountain commented 2 years ago

hey @gk061090 - yeah, this is a case where we assume mdy if the dmy value is >12. I know it's a little sloppy. The javascript Date object does this too. The code is here i think - we could remove it, but it would be a breaking change. maybe we should add a option to disable this? I have no strong opinions about it. cheers

jecraig commented 2 years ago

I would advocate for leaving it as is. @gk061090, you can pass in whether you want dmy in the spacetime constructor.

spacetime('12/01/2018', null, { dmy: true }) //jan 12th

gk061090 commented 2 years ago

Thanks. I think it's enough to create an abstraction over spacetime and pass the parameter { dmy: true }. But I also have a problem with yyyy-MM-dd format:

new Date('2022-13-02') // Invalid Date - OK
spacetime("2022-13-02").isValid() // true - "2022-02-13" - incorrect

How can I fix it? Sorry I forgot to write this case in the first message

jecraig commented 2 years ago

There is no 13th month so 2022-13-02 can't be a ymd.

gk061090 commented 2 years ago

Right, and spacetime("2022-13-02").isValid() should be false (not true). Also spacetime("2022-13-02").unixFmt("yyyy-MM-dd") returns "2022-02-13"