简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM