php check if date is valid code example
Example 1: php check if format is date
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
Test cases:
var_dump(validateDate('2013-13-01'));
var_dump(validateDate('20132-13-01'));
var_dump(validateDate('2013-11-32'));
var_dump(validateDate('2012-2-25'));
var_dump(validateDate('2013-12-01'));
var_dump(validateDate('1970-12-01'));
var_dump(validateDate('2012-02-29'));
var_dump(validateDate('2012', 'Y'));
var_dump(validateDate('12012', 'Y'));
Example 2: php check if input is date
function isRealDate($date) {
if (false === strtotime($date)) {
return false;
}
list($year, $month, $day) = explode('-', $date);
return checkdate($month, $day, $year);
}