php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #73644 Datetime::diff returns wrong number of month difference
Submitted: 2016-12-02 16:12 UTC Modified: 2016-12-02 18:05 UTC
From: john dot mannard at yahoo dot fr Assigned: cmb (profile)
Status: Not a bug Package: Date/time related
PHP Version: 7.1.0 OS:
Private report: No CVE-ID: None
 [2016-12-02 16:12 UTC] john dot mannard at yahoo dot fr
Description:
------------
Hi,
I executed this piece of code yesterday and have the feeling there may be a problem in how Datetime object parses strings. 
The "new DateTime()" instruction returns a DateTime object with current date. The "new DateTime('yyyy-mm-dd') return a DateTime object with date given. Depending on how you instantiate, interval returned by the diff method will not return same amount of months. 

In code below, if you comment line 2 or not, the m property of DateInterval obkect will not be the same (in one case it is 3, in the other it is 2). 

I have the feeling that these two ways of instantiating a DateTime should process a difference with another the date the same way. 

Am I wrong on this topic?

Thanking you in advance. 

Test script:
---------------
$date1 = new DateTime();
$date1 = new DateTime($date1->format('Y-m-d')); // If commented, not same result in number of months
$threemonthsago = new DateTime('3 months ago');
$diff = $threemonthsago->diff($date1);	
echo 'Number of months: '.($diff->m + 12*$diff->y );echo '<br/>';
echo '$date1 in d-m-Y format: '.$date1->format('d-m-Y');echo '<br/>';
echo '$threemonthsago in d-m-Y format: '. $threemonthsago->format('d-m-Y');

Expected result:
----------------
In the code above, first echo should always be 3 months. 

Actual result:
--------------
In the code above, if second line is commented, it shows 3, otherwise 2. 

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-12-02 18:05 UTC] cmb@php.net
-Status: Open +Status: Not a bug -Assigned To: +Assigned To: cmb
 [2016-12-02 18:05 UTC] cmb@php.net
The first $date1 and $threemonthsago also include the current time, but the second $date1 does not, see <https://3v4l.org/Ev1BM>. This behavior is intentional, and also the following results.
 [2016-12-05 07:42 UTC] john dot mannard at yahoo dot fr
Thank you for your answer.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 15:01:28 2024 UTC