0

When I want to check that a string is a date in Javascript, I usually do something like:

!isNaN(Date.parse(myString));

But I just discovered that

isNaN(Date.parse("smth")) === true
isNaN(Date.parse("smth_1")) === true
isNaN(Date.parse("1 smth")) === true
isNaN(Date.parse("smth 1")) === false // !!

See this fiddle.

So my question is: why does any string ending with a number (with a space before) parse as a valid date (which it is obviously not), and how to reliably check that it's not ?

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
  • What browser are you using? Firefox doesn't have this issue, but Opera does. – Exelian Jul 08 '15 at 13:57
  • It's because any string passed in will be parsed as a number, and your example will in fact be the same as `new Date("1")`. To see how javascript uses `ToNumber` look at the [**specification**](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3) – adeneo Jul 08 '15 at 13:57
  • Standardize the format you want to parse, and check for that. For example, check to make sure your string is all numbers – Gillespie Jul 08 '15 at 13:58
  • http://stackoverflow.com/questions/27876220/issue-with-date-parse-in-chrome – mplungjan Jul 08 '15 at 13:58
  • @Exelian it's Chrome (mplungjan, you're right) – xlecoustillier Jul 08 '15 at 13:59
  • What format are the input strings? In other words, what do you consider as valid date formats? – light Jul 08 '15 at 14:08

2 Answers2

2

Known Chrome issue:

The spec actually says that date parsing is implementation-dependent, and implementations may make a best guess effort when faced with unknown formats. That's what V8 does. We could be stricter and reject more strings, but it's very low priority.

https://code.google.com/p/chromium/issues/detail?id=124398 https://code.google.com/p/chromium/issues/detail?id=126448

Also

Issue with Date.parse in Chrome

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

According to the Mozilla developer Network:

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.

So this is a case of implementation specific parsing.

Exelian
  • 5,749
  • 1
  • 30
  • 49