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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: victor dot todoran at yahoo dot com
New email:
PHP Version: OS:

 

 [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

Add a Patch

Pull Requests

Add a Pull Request

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: Sat Jun 15 04:01:30 2024 UTC