JavaScript RangeError - Invalid date
Last Updated :
18 Jul, 2024
Improve
This JavaScript exception invalid date occurs if the string that has been provided to Date or Date.parse() is not valid.
Message:
RangeError: invalid date (Edge)
RangeError: invalid date (Firefox)
RangeError: invalid time value (Chrome)
RangeError: Provided date is not in valid range (Chrome)
Error Type:
RangeError
Cause of the Error: An invalid date string is provided to Date or Date.parse() method in the code.
Case 1: Invalid Date String
Error Cause:
Using an incorrectly formatted date string when creating a Date
object.
Example:
let date = new Date("2024-02-30"); // Incorrect usage, invalid date
Output:
RangeError: Invalid date
Resolution of Error:
Ensure that the date string is correctly formatted and represents a valid date.
let date = new Date("2024-02-28"); // Correct usage
console.log(date); // Outputs: Wed Feb 28 2024 00:00:00 GMT+0000 (UTC)
Output
2024-02-28T00:00:00.000Z
Case 2: Invalid Timestamp
Error Cause:
Using an incorrect timestamp that JavaScript cannot interpret as a valid date.
Example:
let date = new Date(-8640000000000001); // Incorrect usage, invalid timestamp
Output:
RangeError: Invalid date
Resolution of Error:
Ensure that the timestamp is within the valid range for JavaScript dates.
let date = new Date(-8640000000000000); // Correct usage, valid timestamp
console.log(date); // Outputs: Wed Sep 13 -271821 00:00:00 GMT+0000 (UTC)
Output
-271821-04-20T00:00:00.000Z
Case 3: Invalid Date Manipulation
Error Cause:
Performing an invalid operation on a Date
object that results in an invalid date.
Example:
let date = new Date("2024-01-01");
date.setMonth(14); // Incorrect usage, invalid month
Output:
RangeError: Invalid date
Resolution of Error:
Ensure that date manipulations result in valid dates.
let date = new Date("2024-01-01");
date.setMonth(11); // Correct usage, valid month
console.log(date); // Outputs: Sun Dec 01 2024 00:00:00 GMT+0000 (UTC)
Output
2024-12-01T00:00:00.000Z