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.
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.
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";