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 troublesome to understand.
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 troublesome to understand.
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:
/*** Check whether the date format is correct ** @ param string $ date * @ param string $ formats the format array to be checked * @ 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 a date. if 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:
Var_dump (checkDateIsValid ("2013-09-10"); // output truevar_dump (checkDateIsValid ("2013-09-ha"); // output falsevar_dump (checkDateIsValid ("2012-02-29 ")); // output truevar_dump (checkDateIsValid ("2013-02-29"); // output false
Reprinted, please note: Happy programming» php thoughts on judging whether the date is valid