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.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);
}
instanceof breaks across frames. Duck-typing can work just fine too: validDate == d && d.getTime && !isNaN(d.getTime()); -- Since the question is for a general utility function I prefer to be more strict.
@Borgar, just found my answer: "The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail."
you don't even need
d.getTime
justisNan(d)
Could be simplified like this:
d instanceof Date && !isNaN(d.getTime())
Thanks for the answer, but I wish to stress @Borgar and @blueprintChris comments: if I parse the digit
1
for example I would still have a valid date resulting toMon Jan 01 2001 00:00:00
which is indeed a date, however for the purpose of my application it is completely useless. Thus, there is some more input validation needed in my case at least. This answer validates adateObject
not aDate
!