1

I'm working on a Date validation function for a custom render in my web app. When I get a string like "abc", what I do is try to parse it to Date using Date.parse() and it returns NaN since it's not parseable. The interesting part comes when I get a string containing some numbers separated as a token of the string (i.e. "abc 1"), the parse built-in method returns a timestamp. I don't understand why this happens. Does JS think it is a date format?

I try different strings to be parsed and it's curious:

Date.parse("abc") => NaN
Date.parse("abc1") => NaN
Date.parse("abc123") => NaN
Date.parse("abc 1") => timestamp
Date.parse("abc 123") => timestamp
Date.parse("abc 123456") => timestamp
Date.parse("abc 1234567") => NaN
const isDate = string => !isNaN(Date.parse(string) /* returns timestamp */);

isDate("abc 123"); // returns true

If someone can tell me the reason why this happen and any suggestion on how to fix this issue without using an extra library (i.e. moment) would be great!

ivandevp
  • 54
  • 6
  • What timestamp do you get? – Lightness Races in Orbit Feb 12 '19 at 00:50
  • For the example provided, the number returned is -58285675404000 – ivandevp Feb 12 '19 at 01:08
  • 1
    a quick read through the [relevant mdn docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) says that basically Date.parse takes and returns pretty inconsistent values, and actually recommends using a date parsing library. My question is why you're allowing users to enter random strings instead of using a date input. When you say "web app", it's kind of assumed you're targetting modern browsers, which means support for built in date inputs with built-in validaton is pretty broad. – Aaron Ballard Feb 12 '19 at 01:40

0 Answers0