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!