Yoshi
Yoshi

Reputation: 27

Strange behaviour with php datetime objects- subtracting from date a second time when calling diff()

When I subtract 1 day from a datetime object, it does as it is supposed to, it subtracts one day. but if I use diff() to compare 2 datetime objects it then subtracts the day again. You can see in the following code example:

$currTime = new DateTime();
$lastPurge = new DateTime("14:33");
$lastPurge->sub(new DateInterval("P1D"));

echo $lastPurge->format("d/m/Y H:i:s\n\n");

$diff = $currTime->diff($lastPurge);

echo $lastPurge->format("d/m/Y H:i:s\n\n");

The output from that code is:

10/11/2010 14:33:00

09/11/2010 14:33:00

As you can see, after calling sub() it has subtracted 1 day, as expected. But then after using diff() it subtracts another day. Why is another day subtracted after using diff() to calculate the difference? Is it supposed to do this?

Upvotes: 1

Views: 498

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284816

Can't reproduce on PHP 5.3.3, with America/New_York time zone:

php > $currTime = new DateTime();
php > $lastPurge = new DateTime("14:33");
php > $lastPurge->sub(new DateInterval("P1D"));
php >
php > echo $lastPurge->format("d/m/Y H:i:s\n\n");
09/11/2010 14:33:00

php >
php > $diff = $currTime->diff($lastPurge);
php >
php > echo $lastPurge->format("d/m/Y H:i:s\n\n");
09/11/2010 14:33:00

You are right that diff says nothing about modifying either input parameter.

EDIT: This is bug 49059. The changelog says the first release with the fix is 5.3.3.

Upvotes: 1

Related Questions