0

I'm still learning PHP and trying to improve in PHP programming. So, I'm testing out a simple code that shows the duration between two dates. I test it with different start dates and end dates until this one got the wrong duration.

Code:

<?php
$d1 = new DateTime('2017-02-20'); // 20 Feb 2017
$d2 = new DateTime('2017-05-12'); // 12 May 2017

$diff = $d2->diff($d1); //excluding end date

echo $diff->y ." years "; 
echo $diff->m ." months ";
echo $diff->d ." days";
?>

The correct duration was supposed to be 0 years 2 months 22 days. But it displayed the wrong duration that is 0 years 2 months 20 days.

Can someone explain to me why is that? I want to know what is the reason why it became like that.

Hazirah_Halim
  • 87
  • 2
  • 16
  • Possible duplicate of [PHP date\_diff function broken?](http://stackoverflow.com/questions/42332227/php-date-diff-function-broken) – user3942918 Apr 04 '17 at 04:33
  • 5
    28 Days in February. 8 days to March 1st + 12 days + 2 months... Seems right to me – Trent Apr 04 '17 at 04:33
  • Possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/q/676824/1255289) – miken32 Apr 04 '17 at 05:17

2 Answers2

0

Correct the code here:

$d1 = new DateTime('2017-02-20'); // 20 Feb 2017
$d2 = new DateTime('2017-05-12'); // 12 May 2017

$diff = $d1->diff($d2); //excluding end date

echo $diff->y ." years "; 
echo $diff->m ." months ";
echo $diff->d ." days";

Always deduct from greater date to less date.

Gaurav
  • 721
  • 5
  • 14
-1

You should differentiate $d1 to $d2

$d1 = new DateTime('2017-02-20');
$d2 = new DateTime('2017-05-12');
$diff = $d1->diff($d2); // differentiate $d1 (datetime1) to $d2 (datetime2)

echo $diff->y ." years "; 
echo $diff->m ." months ";
echo $diff->d ." days";

http://php.net/manual/en/datetime.diff.php

You can try the procedural way also.

$d1 = date_create('2017-02-20');
$d2 = date_create('2017-05-12');
$diff = date_diff($d1, $d2); // differentiate $d1 (datetime1) to $d2 

echo $diff->y ." years "; 
echo $diff->m ." months ";
echo $diff->d ." days";
cletsimon
  • 61
  • 5