Detecting an invalidly parsed date in Javascript

[tweetmeme]
When parsing a date in Javascript, it is important to ensure that the resultant object has been parsed correctly. This is made slightly tricky as the resultant object will always be a Date object if created with new Date().

The problem is compounded by differences between IE and other browsers. IE will return a NaN whereas other browsers will report "Invalid Date".

Use the following code to be sure:

var d = new Date("Malformed date")
if (d != "NaN" && d != "Invalid Date") {
  // date is good
} else {
  // date is bad
}

Does anyone else have any good ways of doing this detection?

Advertisements