I think it should be a simple function to determine whether the date is valid, but it is still a bit cumbersome to think about it, because it is necessary to test the format, but also to check the validity. For example, 2013-02-29, although the format is correct, but the date is invalid, and the 2012-02-29 format is correct, also valid.
A method can use the regular, but the regular is actually very troublesome to understand, and the use of the regular in the test is not very good. Here is a method, mainly using the Strtotime and date functions for testing. Directly on the function:
Copy the Code code as follows:
/**
* Verify that the date format is correct
*
* @param string $date Date
* @param string $formats Array of formats to be inspected
* @return Boolean
*/
function Checkdateisvalid ($date, $formats = Array ("y-m-d", "y/m/d")) {
$unixTime = Strtotime ($date);
if (! $unixTime) {//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
foreach ($formats as $format) {
if (date ($format, $unixTime) = = $date) {
return true;
}
}
return false;
}
The detailed description in the code comment is no longer narrated. One thing to note: If you need a date format that is special, even if the correct format, the Strtotime function can not be resolved, you cannot use this function, but this should be very rare.
Some examples:
Copy the 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