0

I am trying to get difference between dates using this code, but it can not produce the right result, what is wrong with this code, I could not find out.

$birth_date     = new DateTime("1977-03-23");
$current_date   = new DateTime();

$diff           = $birth_date->diff($current_date);

echo $years     = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months    = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks     = floor($diff->days/7) . " weeks " . $diff->d%7 . "  day(s)"; echo "<br/>";
echo $days      = $diff->days . " days"; echo "<br/>";

It shows Outout as - 39 years 10 months 16 days But I think the output should be - 39 years 10 months 7 days

It calculate year and month correctly but days are wrong.

user3384093
  • 45
  • 1
  • 8
  • 2
    Did you consider that there are leap years? – Qirel Feb 08 '17 at 13:01
  • Leap years...? thats always the caveat here – PhpDude Feb 08 '17 at 13:02
  • Ther are 9 leap years between 1977 and 8/Feb/2017 – RiggsFolly Feb 08 '17 at 13:05
  • Can you correct the code according leap years ? – user3384093 Feb 08 '17 at 13:07
  • 1
    But.. Why would you ignore leap years? Some years have 1 extra days, that's how we've defined our calendar. – Qirel Feb 08 '17 at 13:07
  • 1
    Also: I think `$diff->d % 7` is supposed to be `$diff->days % 7` (respectively like the floor in that line) – ccKep Feb 08 '17 at 13:08
  • Qirel, I want to ignore leap years for first output from 39 years 10 months 16 days to 39 years 10 months 7 days, it seems more correct – user3384093 Feb 08 '17 at 13:14
  • 2
    But it *isn't* technically correct, because those leap years did in fact have 366 days (strictly speaking, every year has 365.25 days). Exactly why do you need to ignore leap days? – Qirel Feb 08 '17 at 13:16
  • ok, May be I wrong, but if you calculate difference between 1977/03/23 to today then 39 years is right, 10 months(Till Jan.) is right, but today is 8 Feb, so days should be 7. In second output it can be say correct as 478 months 16 days – user3384093 Feb 08 '17 at 13:25

2 Answers2

0

maybe this function can help you:

function leap_year($date1, $date2)
{
    $y1 = $date1->format('Y');
    if ($date1->format('m')>2) $y1++;

    $y2 = $date2->format('Y');
    if ($date2->format('m')<=2) $y2--;

    $leap_years = 0;
    for($i = $y1; $i <= $y2; $i++)
    {
        //echo date("Y", strtotime($i . '-01-01')).' '.date("L", strtotime($i . '-01-01')).'<br/>';

        if (date("L", strtotime($i . '-01-01')) == 1)
            $leap_years++;
    }
    return $leap_years;
}
echo leap_year($birth_date, $current_date);
Maciej__
  • 159
  • 7
-1

Maybe you missed the leap years, this could explain the difference of 9 days, e.g.

9 * 4 y = 36 years
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198