1

I am unable to understand why javascript is giving valid date equals to 1 dec date when giving invalid date? Is this behaviour incorporated in language for specific reason? because it must be invalid date for my use case new Date("11/31/2017")

Optimus
  • 116
  • 1
  • 7
  • I've never been able to learn all the rules and exceptions of the Date constructor parser. Are you positively sure that it should always reject dates in American format? – Álvaro González Jan 31 '17 at 13:31
  • http://stackoverflow.com/questions/8098202/javascript-detecting-valid-dates – msg Jan 31 '17 at 13:43

1 Answers1

1

First of all, the Date constructor is not designed to validate input, or even to be picky. On the contrary, it's explicitly designed to create an instance at any cost, with creative rules like this:

Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1)

So if you really need to validate dates you need to look somewhere else.

As about 11/31/2017, the constructor expects this:

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

... which looks good. But this follows (emphasis mine):

parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

And if we dig into Date.parse() docs we finally read this:

The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return NaN.

However, invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided, e.g.:

// Non-ISO string with invalid date values
new Date('23/25/2014');

will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7

This fallback case is the one your date fell into.

Community
  • 1
  • 1
Álvaro González
  • 142,137
  • 41
  • 261
  • 360