1

In code below, I don't want the string not_a_date to be whitelisted as a proper date, but rather as NaN or invalid date. but Date.parse returns a proper epoch value.

not_a_date = 'https://www.example.com/2021/03/03'
Date.parse(not_a_date)
// Expected: NaN
// Result: 1614709800000
  • Not looking for a exact format match, but a fuzzy match that still works the same as Date.parse for other cases such as 2020.01.01, 01/10/2020
  • Another function that achieves this also works for me.
Anil
  • 329
  • 2
  • 9
  • 1
    Can't you use a regex to validate date format? – Salman A Nov 23 '21 at 12:29
  • Yes, regex also works but I'm keeping regex as the last resort, as there are lot of combinations for valid date format. If there's a native method that invalidates cases with dangling prefix & suffix – Anil Nov 23 '21 at 12:57
  • Your question is way too vague to expect a useful answer. The behaviour of built–in parsers is almost completely implementation dependent, adding another set of heuristics on top doesn't make a lot of sense. – RobG Nov 23 '21 at 12:59
  • 1
    See [*Detecting an "invalid date" Date instance in JavaScript*](https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript), [*JavaScript Detecting Valid Dates*](https://stackoverflow.com/questions/8098202/javascript-detecting-valid-dates) and [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Nov 23 '21 at 13:02
  • Thanks for the links. yeah I agree its a vague question. just looking out if a more stricter version of parse is provided by API (shouldve mentioned this in question) before going with custom validator for my usecase. – Anil Nov 23 '21 at 13:11

1 Answers1

2

Date.parse is still largely dependant on the browser you're using; your code DOES return NaN in Firefox v94 for example. You'll likely have to write your own parsing function before passing it to Date.parse().

  • If the OP parses the string (either with a bespoke function or library), then there's no need to use Date.parse, which should not be used for any string other than the two formats supported by ECMA-262 (and even then it's problematic). – RobG Nov 23 '21 at 12:56
  • I was thinking more that he would check to see if it is one of those valid strings before parsing it to Date.parse, rather than parsing it into a date themselves, sorry! –  Nov 23 '21 at 12:58
  • So… parse a string to another string to pass to another parser that is implementation dependent. Hmmm. – RobG Nov 23 '21 at 13:01