18

How can I prevent PHP to crash when creating a DateTime object?

$in = new DateTime($in);
$out = new DateTime($out);

$in and $out both comes from a form so they could be anything. I enforce the user to use a calendar and block it to dates with javascript. What if the user can bypass this check?

If $in = "anything else other than a date" PHP will crash and block the rendering of the whole page.

How do I prevent this and just return(0) if PHP is not able to parse the date?

1

4 Answers 4

27

Check out the documentation on DateTime(), here's a little snippet:

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

echo $date->format('Y-m-d');
?>

PHP Manual DateTime::__construct()

Sign up to request clarification or add additional context in comments.

3 Comments

This exception won't be catch, as a fatal error is thrown. See this comment on same documentation page: php.net/manual/en/datetime.construct.php#113342
This is great but any ideas how to catch only Invalid datetime format exception, instead of a generic exception?
Thanks for the explanation, but I'm still mystified as to why php would be written this way. What on earth is the point of making this uncatchable? It seems perverse.
8

strtotime() will return false if the format is bad so this should catch bad formats.

if (strtotime($in) === false)
{
     // bad format
}

1 Comment

This doesn't work for values like "30.11.-1" (which is 0000-00-00), the var_dump is then int(-62169987600).
4

What about exception handling?

try {
    $in = new DateTime($in);
} catch (Exception $e) {
    echo $e->getMessage();
    return(0);
}

1 Comment

Interestingly the class factory DateTime::createFromFormat does not throw an exception when it cannot interpret the string, but instead returns false. It thereby breaks the OOP model
3

The DateTime constructor will throw an Exception if the date/time string cannot be parsed. You can catch it. Have a look at the following snippet:

try   {
    $dt = new DateTime('10th - 12th June 2013'); // bad date string
} catch (Exception $e) {
    var_dump($e->getMessage());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.