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.
Examples
Code that triggers the error
const d = new Date("31/12/2024"); // wrong format
console.log(d.toISOString());Error output
RangeError: Invalid time value
How to fix it
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.
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;
}Related errors
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