Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date.parse method not working correctly

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 ?

like image 940
Nadeem Khedr Avatar asked Mar 08 '13 10:03

Nadeem Khedr


1 Answers

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.

like image 51
nick_w Avatar answered Nov 01 '22 11:11

nick_w