Home >Web Front-end >JS Tutorial >How Can I Reliably Validate JavaScript Date Instances?
Validating Date Instance Validity in JavaScript
Determining the validity of Date instances in JavaScript can be challenging. Let's explore the "invalid date" problem and find a solution to reliably detect invalid Date objects:
The Date object is a JavaScript construct that represents a specific instant in time. Issues arise when creating Date instances from invalid date strings, as shown in the example below:
var d = new Date("foo");
This code produces an "Invalid Date" instance, which is of type object and inherits from the Date prototype. However, Object.prototype.toString.call(d) returns "[object Date]", and d instanceof Date evaluates to true.
Solution:
Here's a straightforward approach to check for valid Date instances:
if (Object.prototype.toString.call(d) === "[object Date]") { if (isNaN(d.getTime())) { // Invalid Date } else { // Valid Date } } else { // Not a Date object }
This method ensures that the instance is a Date object and that its time value is not NaN. If either condition fails, the Date instance is considered invalid.
Update [2018-05-31]:
For cases where Date objects from external contexts are not a concern, a simpler validation function can be used:
function isValidDate(d) { return d instanceof Date && !isNaN(d); }
Note [2021-02-01]:
It's important to note that there is a distinction between "invalid dates" and "invalid date objects". This answer focuses on validating Date instances, not date input strings.
The above is the detailed content of How Can I Reliably Validate JavaScript Date Instances?. For more information, please follow other related articles on the PHP Chinese website!