First of all, it should be a simple function to judge whether the date is effective, but it's still a bit troublesome to think about it, because both the test format and the validity are checked. For example, 2013-02-29, although the format is correct, but the date is invalid, and 2012-02-29 format is correct, also valid.
A method can use regular, but it is actually very difficult to understand, and the use of regular in the test of effectiveness is not very good. A method is provided here, primarily by using the Strtotime and date functions for testing. Directly on the function:
Copy Code code as follows:
/**
* Verify date format is correct
*
* @param string $date Date
* @param string $formats Array of formats that need to be validated
* @return Boolean
*/
function Checkdateisvalid ($date, $formats = Array ("y-m-d", "y/m/d")) {
$unixTime = Strtotime ($date);
if (! $unixTime) {//strtotime conversion is not correct, the date format is clearly incorrect.
return false;
}
Verify the validity of the date, as long as one of the formats is met OK
foreach ($formats as $format) {
if (date ($format, $unixTime) = = $date) {
return true;
}
}
return false;
}
Code comments in the description of the more detailed, it is no longer narrated. One thing to note: If you need a date format that is special, you cannot use this function if the Strtotime function is not resolvable even in the correct format, but this should be very rare.
Some examples:
Copy Code code as follows:
Var_dump (Checkdateisvalid ("2013-09-10")); Output true
Var_dump (Checkdateisvalid ("2013-09-ha")); Output false
Var_dump (Checkdateisvalid ("2012-02-29")); Output true
Var_dump (Checkdateisvalid ("2013-02-29")); Output false