php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #81527 DateTime::diff returns different results when called on both objects.
Submitted: 2021-10-15 11:39 UTC Modified: 2021-10-15 14:46 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:2 (100.0%)
From: victor dot todoran at yahoo dot com Assigned:
Status: Not a bug Package: Date/time related
PHP Version: 7.4.24 OS: Ubuntu 20.04
Private report: No CVE-ID: None
 [2021-10-15 11:39 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-10-15 14:46 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2021-10-15 14:46 UTC] 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-18 08:07 UTC] victor dot todoran at yahoo dot om
Thanks for taking the time to respond and give an example.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Dec 27 00:01:30 2024 UTC