Lingua-e
← Errors
JavaScript

Invalid Date: What It Means and How to Fix It

Error reference

Invalid Date

Language

JavaScript

Severity

Medium

When it happens

An Invalid Date object is silently created when new Date() receives a string it cannot parse.

Potential fixes

Always use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ssZ) for dates. Validate with isNaN(date.getTime()) after construction. Consider using a library like date-fns or Temporal (stage 3) for robust date parsing.

Deep dive

An Invalid Date object is silently created when new Date() receives a string it cannot parse. Operations on it return NaN or throw a RangeError. JavaScript's Date constructor is lenient about what it accepts, but the accepted formats vary across browsers.

Why it happens

  • Passing a date string in DD/MM/YYYY format, which is not reliably parsed.
  • Passing an empty string or null to new Date().
  • Using a locale-specific format that the browser does not recognize.
  • Receiving a date from a user input or API that is malformed.

Potential fixes

Always use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ssZ) for dates. Validate with isNaN(date.getTime()) after construction. Consider using a library like date-fns or Temporal (stage 3) for robust date parsing.

Examples

JavaScript

Code that triggers the error

const d = new Date("31/12/2024"); // wrong format
console.log(d.toISOString());

Error output

RangeError: Invalid time value

Fixed code

// Use ISO 8601 format: YYYY-MM-DD
const d = new Date("2024-12-31");
console.log(d.toISOString()); // "2024-12-31T00:00:00.000Z"

// Always validate first
function parseDate(str) {
  const d = new Date(str);
  return isNaN(d.getTime()) ? null : d;
}

Practice in English

How would you explain an Invalid Date to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free