@whitej71
In the example you gave, it is correctly returning false. The function example is comparing a string to a known date format. I suggest reading the documentation on the date format to see why you're making the wrong assumption.
(PHP 4, PHP 5, PHP 7)
checkdate — 验证一个格里高里日期
$month
, int $day
, int $year
)检查由参数构成的日期的合法性。如果每个参数都正确定义了则会被认为是有效的。
month
month 的值是从 1 到 12。
day
Day
的值在给定的 month
所应该具有的天数范围之内,闰年已经考虑进去了。
year
year 的值是从 1 到 32767。
如果给出的日期有效则返回 TRUE
,否则返回
FALSE
。
Example #1 checkdate() 例子
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
以上例程会输出:
bool(true) bool(false)
@whitej71
In the example you gave, it is correctly returning false. The function example is comparing a string to a known date format. I suggest reading the documentation on the date format to see why you're making the wrong assumption.
The below suggested date validation (from another note) does NOT work for ALL formats and date inputs.
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
A couple of examples should suffice as a warning to test carefully and particularly not to use code that allows passing in of just any date format string:
var_dump(validateDate('7/01/16', 'n/j/y')); # false but should be true
var_dump(validateDate('7/1/16', 'm/d/y')); # false but should be true
Sorry, I don't have a suggested correction.
With DateTime you can make the shortest date&time validator for all formats.
<?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')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true
var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); # true
# or
var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); # true
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # true
# or
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); # true
var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS)); # false
# ...