문제

Why php DateTime object does not give me errors for an invalid date input? For instance,

$date_test = '13-10-31';

$datetime = new DateTime();
$date = $datetime->createFromFormat('Y-m-d', $date_test);
$date_errors = $datetime->getLastErrors();
print_r($date_errors);

result,

Array
(
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

)

I have set the date format to be 'Y-m-d' which is yyyy-mm-dd so '13-10-31' should be an error input isn't?

EDIT

if I change this line $datetime->createFromFormat('Y-m-d', $date_test); to

$datetime->createFromFormat('YY-m-d', $date_test);

I will get an error no matter what I input. For instance,

$date_test = '2013-10-31';

result,

Array
(
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 2
    [errors] => Array
        (
            [4] => Unexpected data found.
            [10] => Data missing
        )

)

Why!??

도움이 되었습니까?

해결책 2

Your date is a valid date, however your code is incorrect in that DateTime::createFromFormat() is a static function as is getLastErrors(). Your example code should be:-

$date_test = '13-10-31';
$date = \DateTime::createFromFormat('Y-m-d', $date_test);
$date_errors = \DateTime::getLastErrors();
print_r($date_errors);

However, there will still be no errors as the 31st October 13 (13-10-31) is a valid date. When you provide '13' as the year, DateTime casts it to an integer, 13, therefore, it is a valid year.

If you want to discard double digit years as invalid, then you will have to write your own validation functions.

I would recommend a thorough read of the PHP Date and Time extensions documentation

다른 팁

echo $date->format('d-m-Y') showed 31-10-0013, so looks like php threating your date as normal.


UPDv1:

This is not mentioned in docs. Still if you look into echo $date->format('U'); it will give you a negative timestamp.

Since PHPv5.3.0 this feature is confirmed, according to 3v4l test.

this is not because of the date inputted but by the incorrect defination of Year parameter.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top