Home > Web Front-end > JS Tutorial > How Can I Reliably Detect Invalid JavaScript Date Objects?

How Can I Reliably Detect Invalid JavaScript Date Objects?

Susan Sarandon
Release: 2024-12-13 00:54:09
Original
173 people have browsed it

How Can I Reliably Detect Invalid JavaScript Date Objects?

Detecting Invalid Date Instances in JavaScript

Determining whether a JavaScript Date object is valid can be a challenge. Despite appearing as objects, invalid dates return "Invalid Date" upon string conversion. This discrepancy between instanceof Date and console.log output poses a problem for developers.

Solution: Checking for NaN Time Value

One reliable method for detecting invalid dates is to test for NaN as the time value. Within the Date object, NaN indicates an invalid date, whereas valid dates have a valid time value. This behavior is documented in the ECMA-262 standard.

Code Example:

Simplified Version:

Note that this solution only validates Date objects, not date input. Invalid dates, such as "2013-13-32," are distinct from invalid Date instances.

The above is the detailed content of How Can I Reliably Detect Invalid JavaScript Date Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template