php USES the strtotime and date functions to determine if the date is valid code share
- 2020-11-26 18:44:14
- OfStack
At first glance, it should be a simple function to determine whether the date is valid or not, but it is a bit cumbersome to think about because you have to check the format as well as the validity. For example, 2013-02-29, although the format is correct, but the date is invalid; 2, 2012, 29.
1 You can use regularization, but regularization is a bit of a hassle to understand, and it's not a great way to check validity. Here is a method that USES the strtotime and date functions primarily for validation. Directly on the function:
/**
* Verify that the date format is correct
*
* @param string $date The date of
* @param string $formats An array of formats to verify
* @return boolean
*/
function checkDateIsValid($date, $formats = array("Y-m-d", "Y/m/d")) {
$unixTime = strtotime($date);
if (!$unixTime) { //strtotime The conversion is wrong, and the date format is obviously wrong.
return false;
}
// Verify the validity of the date as long as it satisfies it 1 A format to be OK
foreach ($formats as $format) {
if (date($format, $unixTime) == $date) {
return true;
}
}
return false;
}
The code comment is more detailed, I will not talk about it. One thing to note: If you need a date with a special format that the strtotime function cannot parse, even with the correct format, you should not use this function, but this should be very rare.
1 Some examples:
var_dump(checkDateIsValid("2013-09-10")); // The output true
var_dump(checkDateIsValid("2013-09-ha")); // The output false
var_dump(checkDateIsValid("2012-02-29")); // The output true
var_dump(checkDateIsValid("2013-02-29")); // The output false