使用 DateTime,您可以为所有格式创建最短的日期和时间验证器。
<?php
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
var_dump(validateDate('2012-02-28 12:12:12')); var_dump(validateDate('2012-02-30 12:12:12')); var_dump(validateDate('2012-02-28', 'Y-m-d')); var_dump(validateDate('28/02/2012', 'd/m/Y')); var_dump(validateDate('30/02/2012', 'd/m/Y')); var_dump(validateDate('14:50', 'H:i')); var_dump(validateDate('14:77', 'H:i')); var_dump(validateDate(14, 'H')); var_dump(validateDate('14', 'H')); var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS));