Viewed   99 times

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?



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

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

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

PHP Manual DateTime::__construct()

Saturday, August 6, 2022

You need to use the ISO-8601 week numbering year which is o if you want the year for the ISO-8601 week. From the docs:

ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)

$dueDate->format('W , o');
Thursday, December 15, 2022

Why it's not a bug:

The current behavior is correct. The following happens internally:

  1. +1 month increases the month number (originally 1) by one. This makes the date 2010-02-31.

  2. The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd.

How to get what you want:

To get what you want is by: manually checking the next month. Then add the number of days next month has.

I hope you can yourself code this. I am just giving what-to-do.

PHP 5.3 way:

To obtain the correct behavior, you can use one of the PHP 5.3's new functionality that introduces the relative time stanza first day of. This stanza can be used in combination with next month, fifth month or +8 months to go to the first day of the specified month. Instead of +1 month from what you're doing, you can use this code to get the first day of next month like this:

$d = new DateTime( '2010-01-31' );
$d->modify( 'first day of next month' );
echo $d->format( 'F' ), "n";

This script will correctly output February. The following things happen when PHP processes this first day of next month stanza:

  1. next month increases the month number (originally 1) by one. This makes the date 2010-02-31.

  2. first day of sets the day number to 1, resulting in the date 2010-02-01.

Tuesday, October 25, 2022

This seems to work, although it seems illogical that documents the microsecond specifier yet doesn't really support it:

function getTimestamp()
        return date("Y-m-dTH:i:s") . substr((string)microtime(), 1, 8);
Friday, October 14, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :