Skip to content Skip to sidebar Skip to footer

Javascript Date.parse Assumes 31 Days In February And All Months?

It seems to me that Date.parse assumes all months have 31 days. Including months with 30 days and including February(which should only ever have 28/29 days). I checked this questio

Solution 1:

According to the specification for Date.parse() (emphasis mine):

The function first attempts to parse the format of the String according to the rules called out in Date Time String Format. […] Unrecognisable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

And according to the specification for Date Time String Format (emphasis mine):

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

Where the fields are as follows: […] DDis the day of the month from 01 to 31.

Therefore, any date with a day of month greater than 31 is illegal and Date.parse() returns NaN.

Please notice that the standard defines a date format, not a date: the static method isn't required to make additional verifications, and everything else is implementation-specific. For instance, Date.parse('2013-02-30') and Date.parse('2013-04-31') both return NaN on Firefox.

Solution 2:

The implementation differs between browsers. IE, Edge and Chrome will parse strings that doesn't represent actual dates, but Firefox will return NaN for those strings. The safe thing to do is to consider the result from Date.parse as undefined for date strings where the day falls outside the range of the month.

Browsers that allow parsing of non-existent dates will return a different date. Parsing "2015-04-31" will return the date 2015-05-01. This is the same behaviour as when using new Date(2015, 3, 31), where numbers out of range is allowed and will wrap around into a different month or year. That means that the result is still usable, if you don't mind that some invalid dates turn into other dates in some browsers.

The standard isn't very clear about what values are valid:

Illegal values (out-of-bounds as well as syntax errors) in a format string means that the format string is not a valid instance of this format.

The day component is defined as having a range from 1 to 31:

DD is the day of the month from 01 to 31.

However, the format is based on ISO 8601, and that is not a format for parsing strings into dates, that is a format for representing dates as string. Clearly you can't represent a date that doesn't even exist as a string.

Post a Comment for "Javascript Date.parse Assumes 31 Days In February And All Months?"