Bug #81527 [Com]: DateTime::diff returns different results when called on both objects.
Edit report at https://bugs.php.net/bug.php?id=81527&edit=1
ID: 81527
Comment by: victor dot todoran at yahoo dot om
Reported by: victor dot todoran at yahoo dot com
Summary: DateTime::diff returns different results when called
on both objects.
Status: Not a bug
Type: Bug
Package: Date/time related
Operating System: Ubuntu 20.04
PHP Version: 7.4.24
Block user comment: N
Private report: N
New Comment:
Thanks for taking the time to respond and give an example.
Previous Comments:
------------------------------------------------------------------------
[2021-10-15 14:46:05] requinix@php.net
The number of days *is* the same.
echo $diff1->days; // 730
echo $diff2->days; // 730
What's different is the *representation* of those days.
2015-10-25
+ 1 year = 2016-10-25
+ 11 months = 2017-09-25
+ 29 days = 2017-10-24
2017-10-24
- 1 year = 2016-10-24
- 11 months = 2015-11-24
- 30 days = 2015-10-25
Dates are hardâ¢.
Advice: humans typically measure differences by counting from the lower number to the higher number
so you'll probably want to use $diff1.
------------------------------------------------------------------------
[2021-10-15 11:39:04] victor dot todoran at yahoo dot com
Description:
------------
DateTime::diff returns different results when called on both objects.
Test script:
---------------
<?php
$date1 = new \DateTime('2015-10-25', new \DateTimeZone('UTC'));
$date2 = new \DateTime('2017-10-24', new \DateTimeZone('UTC'));
$diff1 = $date1->diff($date2);
$diff2 = $date2->diff($date1);
echo $diff1->y . ' years ' . $diff1->m . ' months ' . $diff1->d .
' days '; // outputs 1 years 11 months 29 days
echo PHP_EOL;
echo $diff2->y . ' years ' . $diff2->m . ' months ' . $diff2->d .
' days '; // outputs 1 years 11 months 30 days
Expected result:
----------------
1 years 11 months 29 days
1 years 11 months 29 days
or
1 years 11 months 30 days
1 years 11 months 30 days
I would expect the number of days to be identical.
Actual result:
--------------
The number of days differs
1 years 11 months 29 days
1 years 11 months 30 days
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=81527&edit=1
Thread (3 messages)