Home > Web Front-end > JS Tutorial > How Can I Reliably Validate JavaScript Date Instances?

How Can I Reliably Validate JavaScript Date Instances?

Patricia Arquette
Release: 2024-12-11 02:06:10
Original
319 people have browsed it

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");
Copy after login

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
}
Copy after login

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);
}
Copy after login

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!

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