Datetime Trap

When using Datetime objects, be aware that methods that return the modified date are actually returning the object itself. This means that calculating a difference with diff(), add(), modify() methods also changes the underlying object.

This trap is also set in packages that are build on top of Datetime.

To avoid this trap, use the DatetimeImmutable class. This class is not modified by those methods, but returns a new object every time.

<?php

    $today = new Datetime('now');
    print $today->format('d-m-Y').PHP_EOL;
    // for example, 24-11-2026

    $tomorrow = $today->add(new DateInterval('P1D'));
    print $tomorrow->format('d-m-Y').PHP_EOL;
    // 25-11-2026 (as expected)

    $twoDaysLater = $today->add(new DateInterval('P2D'));
    print $twoDaysLater->format('d-m-Y');
    // 27-11-2026 (one day overshoot!)

?>

Documentation

See also I just fell into the Date Trap in PHP, PHP DateTime difference – it’s a trap! and What’s all this “immutable date” stuff, anyway?.

Related : DateTime, DateInterval, Dates, Days In Month