Home >Web Front-end >JS Tutorial >How Can I Programmatically Verify the Validity of a Date?

How Can I Programmatically Verify the Validity of a Date?

DDD
DDDOriginal
2024-12-06 00:06:10278browse

How Can I Programmatically Verify the Validity of a Date?

How to verify a date's validity

Validating a date's accuracy is crucial, as invalid entries like "2/30/2011" can lead to errors. Here's a method to validate dates:

To validate a date string, convert it to a date object and test it. For example:

// Expect input as d/m/y
function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2], bits[1] - 1, bits[0]);
  return d && (d.getMonth() + 1) == bits[1];
}

['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
  console.log(s + ' : ' + isValidDate(s))
})

This code will print the validity of the given dates:

0/10/2017 : false
29/2/2016 : true
01/02 : true

In this example, "0/10/2017" is invalid as there's no zeroth month, while "29/2/2016" and "01/02" are valid dates.

The above is the detailed content of How Can I Programmatically Verify the Validity of a Date?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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