I want my API to accept Date
objects and need a reliable way to check if a given date is valid. For example:
var d = new Date("foo");
console.log(d.toString()); // 'Invalid Date'
console.log(typeof d); // 'object'
console.log(d instanceof Date); // true
What’s the best way to write an isValidDate
function that works across browsers and accurately detects an invalid Date object?
I’ve been working with JavaScript for several years, and one solid trick I often rely on for detecting a javascript invalid date
is using getTime()
alongside isNaN
.
Here’s the core idea:
function isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
var d = new Date("foo");
console.log(isValidDate(d)); // false
var validDate = new Date();
console.log(isValidDate(validDate)); // true
Why this works:
It ensures the input is truly a Date
object.
It uses getTime()
, which returns NaN
if the date is invalid — a reliable browser-independent check.
This approach has been my go-to in most projects.
That’s a great starting point, Yanisleidi! I’d like to add something here based on my own experience working on APIs that handle lots of date inputs.
Another handy way to catch a javascript invalid date
is by leveraging the string conversion of the date:
function isValidDate(date) {
return date instanceof Date && date.toString() !== "Invalid Date";
}
var d = new Date("foo");
console.log(isValidDate(d)); // false
var validDate = new Date();
console.log(isValidDate(validDate)); // true
This works because JavaScript’s toString()
gives 'Invalid Date'
when the date object is bad.
Caveat: While it’s easy to read and understand, it’s not always as robust as the getTime()
approach, especially if you’re working across multiple environments or browsers where string representations might vary slightly.
Still, it can be useful in simple checks or layered on top of the getTime()
method for extra clarity.
Thanks, Alveera — that’s a useful enhancement! I’d like to build on both your points with something I’ve used in cross-platform projects.
For the most consistent javascript invalid date
check — especially when you can’t fully trust browser quirks — I recommend using Object.prototype.toString
. This checks the internal [[Class]]
of the object, making sure it’s truly a Date
:
function isValidDate(date) {
return Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date);
}
var d = new Date("foo");
console.log(isValidDate(d)); // false
var validDate = new Date();
console.log(isValidDate(validDate)); // true
Why this matters:
- It avoids relying solely on
instanceof
, which can fail across different execution contexts (like iframes).
- It combines the robust type check with the NaN check, covering both identity and validity.
In production systems or shared libraries, this is often the most reliable and future-proof way to detect a javascript invalid date
.