Question

I am using a method to check if a date is valid or not in my application

myApp.isValidDate = function(date) {
  var timestamp;
  timestamp = Date.parse(date);
  if (isNaN(timestamp) === false) {
    return true;
  }
  return false;
};

It works correctly in most cases but when i enter value like "something.com Eq Phone 1" Date.parse returns 978300000000 and the method returned true

how did it parse it as an actual date ?

Was it helpful?

Solution

This behavior was not consistent across browsers. In IE9 and FireFox, Nan was correctly returned, but in Chrome, it seemed to think something.com Eq Phone 1 was January 1st, 2001.

I've not used this library myself, but why not check out DateJS? I copied in something.com Eq Phone 1 to their demo and it did not produce a valid date.

Edit:

As to why this is happening, looking at the date parsing source code from Chromium, we can see these comments:

Any unrecognized word before the first number is ignored.

And

MM and DD defaults to 01 if missing

mm, ss, and sss default to 00 if missing

Which would explain why it managed to convert (essentially) the number 1 into a valid date.

Edit 2:

So to clarify, the number in something.com Eq Phone 1 appears to indicate the month. For example, changing the 1 to a 3 gives March 1, 2001.

At this stage I can't find any hard evidence that the year defaults to 2001.

OTHER TIPS

This appears to be a quirk with Chrome's implementation of parse.date as you can see here:

http://jsfiddle.net/feZ9P/1/

"something.com" is false
"something.com is invalid" is false
"something.com eq phone" is false
"something.com eq phone 1" is true
"something.com eq phone 5" is true
"anything that has one at the end 1" is true
"as long as 1 isn't earlier in the string 1" is false

It only seems to occur if there is a number attached at the end of the string, if there isn't this error doesn't seem to occur.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top