check if string can be date php 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: check if date is past php
$date = new DateTime($event['date']);
$now = new DateTime();
if($date < $now) {
echo 'Date is in the past';
}