Last updated: Mar 2, 2024
Reading timeยท2 min
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();
Check the error message in your browser's console or your terminal (if using Node.js).
The screenshot shows that the error occurred in the index.js
file on line 5
.
The Date() constructor returns an "invalid date" value when the provided string 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 ...
A common cause of the error is trying to use a timestamp value that is of type
string to create a Date
object.
// ๐๏ธ this is a string const timestamp = '1675964045493'; const date = new Date(timestamp); console.log(date); // Invalid Date
Note that the timestamp in the example is a string.
To solve the error, use the parseInt
method to convert the string to an
integer when calling the Date()
constructor.
const timestamp = '1675964045493'; const date = new Date(parseInt(timestamp)); console.log(date); // 2023-02-09T17:34:05.493Z console.log(date.toISOString()); // 2023-02-09T17:34:05.493Z
We used the parseInt
function to convert the timestamp string to an integer
when calling new Date()
which resolved the issue.
Here's a function that you can use to validate a date before calling 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
getTime()
method will return an NaN
(not a number) value.We check if the value is not NaN
and return the result. If the value isn't
NaN
, we have a valid date on which we can safely call methods.
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.
I've also written a detailed guide on how to validate a date in JavaScript.