1

This answer gives a good way to check for dates in JavaScript:

function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}

However, this isn't working for me in Chrome because it identifies strings that contain numbers as dates:

function getDate(str) {
  console.log(new Date(str).toLocaleString());
}

getDate("a string that contains the number 1");
getDate("a string that contains the number 12");
getDate("a string that contains the number 123");
getDate("a string that contains the number 1234");
getDate("a string that contains the number 12345");
getDate("a string that contains the number 123456");
getDate("a string that contains the number 1234567"); // in Chrome, only this one returns "Invalid Date"

What would be the best way to implement a stricter date checker that would work with Chrome's flexible date parsing? I cannot use anything that requires the dates to be formatted in a specific way (e.g., that only accepts ISO 8601 formats).

Dominus.Vobiscum
  • 702
  • 1
  • 9
  • 16
  • `d instanceof Date` is not a good way to check for a Date as it will [fail across frames and documents](https://stackoverflow.com/search?q=%5Bjavascript%5D+instanceof+fails) due to different execution contexts, see https://stackoverflow.com/a/1353711/257182 for a much better way. – RobG Mar 02 '19 at 09:42
  • @RobG Good to know about `instanceof` between windows, thanks. But the question you linked to as a duplicate doesn't really solve my problem. I know `new Date()` and `Date.parse` are implementation-dependent, but I still need a way to force Chrome to be stricter, and [the top answer](https://stackoverflow.com/a/2587398/9069356) on the duplicated question just says "I would recommend that date strings are parsed manually", which isn't an option in my case. – Dominus.Vobiscum Mar 04 '19 at 16:37
  • As noted in the duplicate, built–in parsers are implementation dependent. There are many questions about validating date strings, maybe [*How to validate a date?*](https://stackoverflow.com/questions/5812220/how-to-validate-a-date) has your answer. – RobG Mar 04 '19 at 21:31

1 Answers1

0

Without controlling what the format is, you're going to have a hard time parsing it, and you may get wrong data. For example, in a lot of other countries, the month and day are switched. So if you have a date that's 11/11, you don't know which is the month.

That being said, I would use a library rather than try and reinvent the wheel of date parsing. Moment.js is pretty good, and will tell you if it thinks the date string is valid: https://momentjs.com/docs/#/parsing/string/

frodo2975
  • 10,340
  • 3
  • 34
  • 41
  • Moment.js behaves the same way unless one explicitly specifies a format. But very good point about 11/11. There may not be any way to do what I'm asking. :-/ – Dominus.Vobiscum Mar 04 '19 at 16:39