Skip to content

RangeError: Invalid Date

Error message

                Invalid Date
              

Quick summary

You passed an invalid value to the Date constructor, resulting in an Invalid Date object that returns NaN for all methods.

Why this happens

  • Passed a malformed date string to new Date()

  • Used an invalid date like February 31st

  • Passed a non-date value that cannot be parsed

Minimal example

✗ Broken code
const date = new Date("not-a-date");
console.log(date.getTime()); // NaN
✓ Fixed code
const date = new Date("2024-01-15");
if (isNaN(date.getTime())) {
  console.log("Invalid date");
} else {
  console.log(date.getTime());
}

Invalid date strings produce an Invalid Date object. Always check with isNaN(date.getTime()).

How to diagnose

  • Check the value being passed to new Date()

  • Call isNaN(date.getTime()) to check if the date is invalid

  • Log the date object — it shows 'Invalid Date' if the input was bad

How to fix

  • Validate the date string format before creating a Date

  • Use isNaN(date.getTime()) to detect invalid dates and provide a fallback

  • Parse date components separately (year, month, day) for reliability

How to prevent

  • Validate date inputs before constructing Date objects

  • Use a date library (date-fns, luxon) for reliable parsing

Related Resources

Related Glossary

Related Lessons

← Back to language