Datetime Trap

When using Datetime objects, be aware that methods that returns the modified date is 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 each time.

<?php

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

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

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

?>

Documentation

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

Related packages : nesbot/carbon, cakephp/chronos