Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Luke Porter
The "Uncaught RangeError: Invalid time value" error occurs when calling a
method on an invalid date, e.g. new Date('asdf').toISOString()
. To solve the
error, conditionally check if the date is valid before calling the method on
it.
Here's an example of how the error occurs:
console.log(new Date('asdf')); // 👉️ "Invalid Date" // ⛔️ Uncaught RangeError: Invalid time value const d = new Date('asdf').toISOString();
If you can see where exactly the error occurs, check the error message in your browser's console or your terminal (if using Node.js).
The screenshot above shows that the error occurred in the index.js
file on
line 5
.
The Date() constructor returns an "invalid date" value when provided a string that is not a valid date. Calling a method on an invalid date causes the error.
console.log(new Date('asdf')); // 👉️ Invalid Date console.log(new Date('2022-32-33')); // 👉️ Invalid Date console.log(new Date('one-two-20')); // 👉️ Invalid Date
To solve the "Invalid time value" error, only call date methods on valid date objects.
console.log(new Date(1317996123)); // 👉️ Fri Jan 16 ... console.log(new Date('24 September 2022 15:30 UTC')); // 👉️ Sat Sep 24 ...
Here's a function that you can use to validate a date before calling any methods on it.
function dateIsValid(date) { return !Number.isNaN(new Date(date).getTime()); } console.log(dateIsValid(1317996123)); // 👉️ true console.log(dateIsValid('24 September 2022 15:30 UTC')); // 👉️ true console.log(dateIsValid('asdf')); // 👉️ false console.log(dateIsValid('2022-32-33')); // 👉️ false
If the date is invalid, the getTime()
method will return a NaN
(not a
number) value.
We check if the value is not NaN
and return the result. If the value is not
NaN
, we have a valid date on which we can safely call a method.
function dateIsValid(date) { return !Number.isNaN(new Date(date).getTime()); } const date = '2022-32-33'; if (dateIsValid(date)) { console.log(new Date(date).toISOString()); } else { // 👇️ this runs console.log('not a valid date'); }
Before calling the toISOString
method on the date, we validate it. This
enables us to avoid getting the "Invalid time value" range error.