gcblmnop
gcblmnop

Reputation: 77

Dealing with well-formed but invalid dates in PHP DateTime

I'm trying to use PHP's DateTime to validate dates, but DateTime will accept some well-formed but invalid dates like 2015-02-30, which it will turn into March 2, 2015, without throwing an exception. Any suggestions for dealing with this, using DateTime or another method?

Edit: Thank you all for the help! I was handling the errors by catching the exception, but I didn't realize that the exception was only thrown on an error, not a warning, and this kind of input only kicks out a warning.

Upvotes: 3

Views: 249

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78984

Check the errors with DateTime::getLastErrors(). A well formed but invalid date:

$date = '2015-02-30';
DateTime::createFromFormat('Y-m-d', $date);

$errors = DateTime::getLastErrors();
print_r($errors);

Yields:

Array
(
    [warning_count] => 1
    [warnings] => Array
        (
            [10] => The parsed date was invalid
        )

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

)

Whereas a non well formed date $date = '02-30'; yields:

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

    [error_count] => 1
    [errors] => Array
        (
            [5] => Data missing
        )

)

Upvotes: 4

John Conde
John Conde

Reputation: 219864

You can use checkdate() to check if the date is valid before using DateTime():

$parts = explode('-', '2015-02-30'); 
if (checkdate($parts[1], $parts[2], $parts[0])) {
    // DateTime() stuff here
}

Demo

Upvotes: 2

Related Questions