1function validateDate($date, $format = 'Y-m-d')
2{
3 $d = DateTime::createFromFormat($format, $date);
4 // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
5 return $d && $d->format($format) === $date;
6}
7
8Test cases:
9var_dump(validateDate('2013-13-01')); // false
10var_dump(validateDate('20132-13-01')); // false
11var_dump(validateDate('2013-11-32')); // false
12var_dump(validateDate('2012-2-25')); // false
13var_dump(validateDate('2013-12-01')); // true
14var_dump(validateDate('1970-12-01')); // true
15var_dump(validateDate('2012-02-29')); // true
16var_dump(validateDate('2012', 'Y')); // true
17var_dump(validateDate('12012', 'Y')); // false
1if (preg_match("/\d{4}\-\d{2}-\d{2}/", $date)) {
2 echo 'true';
3} else {
4 echo 'false';
5}
1function isRealDate($date) {
2 if (false === strtotime($date)) {
3 return false;
4 }
5 list($year, $month, $day) = explode('-', $date);
6 return checkdate($month, $day, $year);
7}
8