Confidently Parsing Dates in Browsers

Its not as easy as it seems to confidently detect certain object types in the browser — especially if you want to make your code as browser agnostic as you can make it. But here is what I’ve found to work the best.

isNaN(new Date('d'))

If that returns false it would mean that you have a valid date object; true means you gave the browser some rubbish and it can’t understand the junk that you fed it.

I’ve tested this in IE (6+), FF, Saf and Chr and the results are all consistent. Other methods of testing for Date objects are not so consistent mainly because IE breaks the mold in all scenarios. These other approaches include

  • new Date('d').getTime()
  • new Date('d').getTime().toString()
  • new Date('d').toString()
  • !!new Date('d').getTime
  • Date.parse('d')
  • Date.parse('d').toString()

I’ve tried’em all. Don’t do it. You’ll get nowhere.

If you want it as a jQuery plugin, then here you go.

$.isDate = function(dateVal) {
   if(isNaN(dateVal * 1)) {
      return !isNaN(new Date(dateVal));
   }

   return !isNaN(new Date(dateVal * 1));
};

In case you were curious, isNaN(new Date('d')) returns false.

Advertisements