Detecting an "invalid date" Date instance in JavaScript
Here's how I would do it:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d.getTime())) { // d.valueOf() could also work
// date is not valid
} else {
// date is valid
}
} else {
// not a date
}
Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
Instead of using new Date()
you should use:
var timestamp = Date.parse('foo');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
}
Date.parse()
returns a timestamp, an integer representing the number of milliseconds since 01/Jan/1970. It will return NaN
if it cannot parse the supplied date string.
You can check the validity of a Date
object d
via
d instanceof Date && isFinite(d)
To avoid cross-frame issues, one could replace the instanceof
check with
Object.prototype.toString.call(d) === '[object Date]'
A call to getTime()
as in Borgar's answer is unnecessary as isNaN()
and isFinite()
both implicitly convert to number.
My solution is for simply checking whether you get a valid date object:
Implementation
Date.prototype.isValid = function () {
// An invalid date object returns NaN for getTime() and NaN is the only
// object not strictly equal to itself.
return this.getTime() === this.getTime();
};
Usage
var d = new Date("lol");
console.log(d.isValid()); // false
d = new Date("2012/09/11");
console.log(d.isValid()); // true