I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:
var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
Any ideas for writing an isValidDate
function?
EDIT - thanks for the responses!
- Ash recommended
Date.parse
for parsing date strings, which gives an authoritative way to check if the date string is valid. - What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.
EDIT 2
- Ash made me consider not having my API accept
Date
instances at all, this would be easiest to validate. - Borgar suggested testing for a
Date
instance, and then testing for theDate
's time value. If the date is invalid, the time value isNaN
. I checked with ECMA-262 (section 15.9.5.9) and this behavior is in the standard, which is exactly what I'm looking for.
My final function, based on Borgar's solution:
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}