Course contentsShow
← JavaScript
Lesson 1619 of 2,72335. Standard Library and Built-insFree lesson

Invalid Dates and NaN

Recognize that invalid date strings create Date objects where getTime() returns NaN, requiring validation checks.

Invalid Dates and NaN

You'll learn how JavaScript handles bad date strings and why checking for NaN is crucial when working with Date objects.

The Silent Failure Problem

When you pass an invalid date string to the Date constructor, JavaScript doesn't throw an error—it creates a Date object that looks valid but is actually broken. This "Invalid Date" object returns NaN (Not a Number) when you call methods like getTime().

Think of it like ordering food in a language you don't speak well. The waiter nods politely and brings you something, but it's not what you expected. The Date constructor is similarly "polite"—it always gives you back a Date object, even when your input makes no sense.

Why This Matters

const badDate = new Date("not-a-date");
console.log(badDate); // Invalid Date (shows as a Date object!)
console.log(badDate.getTime()); // NaN

const anotherBad = new Date("2023-13-45"); // Month 13, day 45?
console.log(anotherBad.getTime()); // NaN

The object exists, but its internal time value is NaN. Any math operations or comparisons will fail silently.

Validating Dates

Always check if a Date is valid before using it:

function isValidDate(date) {
  return !isNaN(date.getTime());
}

const userInput = new Date("2023-02-30"); // Feb 30 doesn't exist
if (isValidDate(userInput)) {
  console.log("Date is good!");
} else {
  console.log("Invalid date detected!");
}

You can also check with isNaN() directly on the result of getTime(), or even date.toString() which returns "Invalid Date" for bad dates.

Key Takeaway: Invalid date strings create Date objects where getTime() returns NaN—always validate dates from external sources before performing operations on them.