Detecting Invalid JavaScript Date Instances
Determining the validity of Date objects in JavaScript can be tricky. One may be tempted to check the object's type and instanceof operator, but these methods are insufficient.
JavaScript's Notion of "Invalid Dates"
Unlike some languages, JavaScript does not explicitly differentiate between valid and invalid dates. Instead, it represents invalid dates as objects with a time value of NaN (Not-a-Number).
Defining an isValidDate Function
To check if a Date object is valid, we can use the following steps:
If both conditions are met, the Date object is considered invalid.
Implementation
Here is an implementation of the isValidDate function:
function isValidDate(d) { if (Object.prototype.toString.call(d) === "[object Date]") { return !isNaN(d); } else { return false; } }
Alternative for Same-Context Date Objects
If you are only working with Date objects created within the same JavaScript context, a simpler version of the function can be used:
function isValidDate(d) { return d instanceof Date && !isNaN(d); }
Note on "Invalid Dates"
It's important to note that this function only validates whether a Date object is valid, not whether the date itself is valid (e.g., 2013-13-32). For input date validation, different methods are required.
The above is the detailed content of How Can I Reliably Detect Invalid JavaScript Date Instances?. For more information, please follow other related articles on the PHP Chinese website!