Detecting an "invalid date" Date instance in JavaScript
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?
Date.parse
for parsing date strings, which gives an authoritative way to check if the date string is valid. Date
instances at all, this would be easiest to validate. Date
instance, and then testing for the Date
's time value. If the date is invalid, the time value is NaN
. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for. 以下是我的做法:
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
}
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.
上一篇: Java日期与日历