- RangeError:недействительная дата
- Message
- Error type
- Что пошло не так?
- Examples
- Invalid cases
- Valid cases
- See also
- Нашли проблему на этой странице?
- RangeError: invalid date
- Message
- Error type
- What went wrong?
- Examples
- Invalid cases
- Valid cases
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to Detect an “Invalid Date” Date Instance in JavaScript?
- instanceof and isNaN
- Date.parse
- instanceof and isFinite
- Conclusion
- JavaScript — detecting invalid date
- 1. Date object test example
- 2. getTime() or other getter test example
- 3. toString() method test example
- 4. Detecting correct date string or date object example
- Alternative titles
RangeError:недействительная дата
Исключение JavaScript «недопустимая дата» возникает, когда строка, ведущая к недопустимой дате, была предоставлена для Date или Date.parse() .
Message
RangeError: Invalid time value (V8-based) RangeError: invalid date (Firefox) RangeError: Invalid Date (Safari)
Error type
Что пошло не так?
Строка, ведущая к недопустимой дате, была предоставлена Date или Date.parse() .
Examples
Invalid cases
Нераспознаваемые строки или даты, содержащие недопустимые значения элементов в строках в формате ISO, обычно возвращают NaN . Однако, в зависимости от реализации, несоответствующие строки формата ISO также могут RangeError: invalid date , как в следующих случаях в Firefox:
new Date('foo-bar 2014'); new Date('2014-25-23').toISOString(); new Date('foo-bar 2014').toString();
Это, однако, возвращает NaN в Firefox:
Date.parse('foo-bar 2014'); // NaN
Дополнительные сведения см. Date.parse() документации Date.parse () .
Valid cases
new Date('05 October 2011 14:48 UTC'); new Date(1317826080); // Метка времени Unix за 5 октября 2011 г., 14:48:00 UTC
See also
Нашли проблему на этой странице?
Last modified: Jul 14, 2022 , авторы MDN
JavaScript
Исключение JavaScript «недопустимый синтаксис BigInt» возникает, когда строковое значение приводится к, но не удалось проанализировать целое число.
Исключение JavaScript «недопустимое присвоение константе» возникает при попытке изменить постоянное значение.
Исключение только для строгого режима JavaScript «объявления заголовка цикла for-in могут не иметь инициализаторов» возникает, когда of содержит выражение, например (var 0
Объявление исключения JavaScript в заголовке цикла for-of не может иметь инициализатор» возникает, когда содержит такое выражение (const 0 iterable).
RangeError: invalid date
The JavaScript exception «invalid date» occurs when a string leading to an invalid date has been provided to Date or Date.parse() .
Message
RangeError: Invalid time value (V8-based) RangeError: invalid date (Firefox) RangeError: Invalid Date (Safari)
Error type
What went wrong?
A string leading to an invalid date has been provided to Date or Date.parse() .
Examples
Invalid cases
Unrecognizable strings or dates containing illegal element values in ISO formatted strings usually return NaN . However, depending on the implementation, non–conforming ISO format strings, may also throw RangeError: invalid date , like the following cases in Firefox:
new Date("foo-bar 2014"); new Date("2014-25-23").toISOString(); new Date("foo-bar 2014").toString();
This, however, returns NaN in Firefox:
For more details, see the Date.parse() documentation.
Valid cases
new Date("05 October 2011 14:48 UTC"); new Date(1317826080); // Unix Timestamp for 05 October 2011 14:48:00 UTC
See also
Found a content problem with this page?
This page was last modified on Feb 21, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How to Detect an “Invalid Date” Date Instance in JavaScript?
If we’re trying to parse JavaScript dates, sometimes we may get ‘invalid date’ values.
If we try to parse invalid date values, then our JavaScript program may crash.
In this article, we’ll look at how to detect an ‘invalid date’ date instance with JavaScript.
instanceof and isNaN
We can combine the use of the instanceof operator and the isNaN function to check for invalid dates.
The instanceof operator lets us whether an object is created from the Date constructor.
And the isNaN function lets us check whether the object converts to a timestamp when we try to cast it to a number.
isNaN tries to cast an object to a number before checking if it’s a number.
const isValidDate = (d) => < return d instanceof Date && !isNaN(d); >const validDate = new Date(2021, 1, 1) const invalidDate = new Date('abc') console.log(isValidDate(validDate)) console.log(isValidDate(invalidDate))
to create the isValidDate function which returns the expression d instanceof Date && !isNaN(d); to do both checks.
Then we can call it with validDate and invalidDate , which are valid and invalid date objects respectively.
Date.parse
We can also use the Date.parse method to try to parse a Date instance into a date.
For instance, we can write:
const validDate = new Date(2021, 1, 1) const invalidDate = new Date('abc') console.log(!isNaN(Date.parse(validDate))) console.log(!isNaN(Date.parse(invalidDate)))
Date.parse returns a UNIX timestamp if it’s a valid date.
So if we pass in validDate to Date.parse , we should get an integer timestamp returned.
And if we pass in invalidDate , we should get NaN returned.
This means we can use isNaN again to check whether the result returned by Date.parse is a number.
instanceof and isFinite
We can call isFinite instead of isNaN in our valid date check.
This is because isFinite only returns true if anything that can be converted to a finite number is passed in as an argument.
const isValidDate = (d) => < return d instanceof Date && isFinite(d); >const validDate = new Date(2021, 1, 1) const invalidDate = new Date('abc') console.log(isValidDate(validDate)) console.log(isValidDate(invalidDate))
This way, we can get rid of the negation before isNaN , which makes the isValidDate function easier to read.
Conclusion
We can check for valid date objects with the instanceof operator, isNaN , isFinite , or Date.parse .
JavaScript — detecting invalid date
Lily
In this article, we’re going to have a look at how to check if data is invalid in JavaScript.
Date correctness can be checked basing on internal state of Date object.
Incorrect date object returns:
- false for call isFinite(myDate) ,
- true for call isNaN(myDate) ,
- NaN from myDate.getTime() method,
- » Invalid Date » string for toString() method call.
// ONLINE-RUNNER:browser; var correctDate = new Date(2020, 10, 15); var incorrectDate = new Date(NaN); // true - means correct // false - means incorrect // console.log( isFinite( correctDate ) ); // true console.log( !isNaN( correctDate ) ); // true console.log( isFinite( incorrectDate ) ); // false console.log( !isNaN( incorrectDate ) ); // false
Look below to see different practical examples:
1. Date object test example
This approach is based on fact: isFinite method returns false for incorrect dates.
// ONLINE-RUNNER:browser; function isCorrectDate(date) < return date instanceof Date && isFinite(date); // return date instanceof Date && !isNaN(date); >// Usage example: var correctDate = new Date(2020, 10, 15); var incorrectDate = new Date(NaN); console.log( isCorrectDate( correctDate ) ); // true console.log( isCorrectDate( incorrectDate ) ); // false
2. getTime() or other getter test example
This approach is based on fact: incorrect date returns NaN values from getters. So we can make a simple test for example with getTime() method.
// ONLINE-RUNNER:browser; function isCorrectDate(date) < return date instanceof Date && isFinite(date.getTime()); // return date instanceof Date && !isNaN(date.getTime()); >// Usage example: var correctDate = new Date(2020, 10, 15); var incorrectDate = new Date(NaN); console.log( isCorrectDate( correctDate ) ); // true console.log( isCorrectDate( incorrectDate ) ); // false
3. toString() method test example
This approach is based on fact: incorrect date object returns » Invalid Date » string for toString() method call. It is good to call to string method with protoype API that prevents methods overriding.
// ONLINE-RUNNER:browser; function isCorrectDate(date) < if (date instanceof Date) < var text = Date.prototype.toString.call(date); return text !== 'Invalid Date'; >return false; > // Usage example: var correctDate = new Date(2020, 10, 15); var incorrectDate = new Date(NaN); console.log( isCorrectDate( correctDate ) ); // true console.log( isCorrectDate( incorrectDate ) ); // false
4. Detecting correct date string or date object example
The example presented in this section allows checking the correctness of the date provided as a string or object. String date should be formatted according to one of the standards:
Run the following code to see the effect:
// ONLINE-RUNNER:browser; function isCorrectDate(date) < return isFinite(date instanceof Date ? date : new Date(date)); // return isFinite(date instanceof Date ? date : Date.parse(date)); // return !isNaN(date instanceof Date ? date : new Date(date)); // return !isNaN(date instanceof Date ? date : Date.parse(date)); >// Usage example: var date1 = '2020-10-15'; var date2 = '2020-10-x5'; //