Invalid Date Instance Detection in JavaScript
Validating date objects in JavaScript can be challenging due to the existence of "invalid date" instances. These objects appear valid (instanceof Date returns true) but represent invalid dates. This article explores various approaches to detecting such instances.
Original Question
The provided code demonstrates the problem:
var d = new Date("foo"); console.log(d.toString()); // shows 'Invalid Date' console.log(typeof d); // shows 'object' console.log(d instanceof Date); // shows 'true'
Recommended Solutions
1. Validate using Date.parse()
Date.parse parses a date string and returns a valid date or NaN if the string is invalid. This can be used to validate date strings before creating a Date object:
if (Date.parse("foo") === NaN) { // invalid date string }
2. Test for NaN Time Value
For existing Date instances, you can test the time value (getTime() or valueOf()):
if (isNaN(d.getTime())) { // invalid Date object }
This method relies on the ECMA-262 specification, which states that an invalid Date object has a NaN time value.
Preferred Code
Based on these recommendations, the following function can be used to validate Date instances:
function isValidDate(d) { return d instanceof Date && !isNaN(d); }
Alternative Method
If you are not concerned with Date objects from external JS contexts, this simpler form may be preferred:
function isValidDate(d) { return d instanceof Date && !isNaN(d); }
Note
This answer focuses on validating Date instances, but it's important to note that it does not cover the validity of date input itself (e.g., 2013-13-32).
The above is the detailed content of How Can I Reliably Detect Invalid Date Instances in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!