In my opinion, judging whether a date is valid should be a simple function, but it is still a little troublesome to think about it, because we need to check both the format and the validity. For example, although the format is correct, but the date is invalid; while is also valid.
One method can use regular expressions, but regular expressions are quite difficult to understand, and they are not very good at verifying validity. Here we provide a method, mainly to use the strtotime and date functions for testing. Direct function:
Copy codeThe Code is as follows:
/**
* Check whether the date format is correct
*
* @ Param string $ date
* @ Param string $ formats the format array to be verified
* @ Return boolean
*/
Function checkDateIsValid ($ date, $ formats = array ("Y-m-d", "Y/m/d ")){
$ UnixTime = strtotime ($ date );
If (! $ UnixTime) {// The strtotime conversion is incorrect. The date format is obviously incorrect.
Return false;
}
// Verify the validity of the date, as long as one of the formats is satisfied, OK
Foreach ($ formats as $ format ){
If (date ($ format, $ unixTime) = $ date ){
Return true;
}
}
Return false;
}
The descriptions in the code comments are more detailed and will not be described. Note: If the required date format is special, the strtotime function cannot be parsed even if it is in the correct format, but this function cannot be used, but this situation should be rare.
Some examples:
Copy codeThe Code is as follows:
Var_dump (checkDateIsValid ("2013-09-10"); // outputs true
Var_dump (checkDateIsValid ("2013-09-ha"); // outputs false
Var_dump (checkDateIsValid ("2012-02-29"); // outputs true
Var_dump (checkDateIsValid ("2013-02-29"); // outputs false