Detecting an "invalid date" Date instance in JavaScript
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.
Here's how I would do it:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
// date object is not valid
} else {
// date object is valid
}
} else {
// not a date object
}
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);
}
Update [2021-02-01]: Please note that there is a fundamental difference between "invalid dates" (2013-13-32
) and "invalid date objects" (new Date('foo')
). This answer does not deal with validating date input, only if a Date instance is valid.