Alex Rivera | Logout

Calculating number of years between 2 dates in PHP

Asked 2011-03-22T05:20:35.917
46

I need to get the number of years from 2 dates provided. Here's my code:

function daysDifference($endDate, $beginDate)
{
   $date_parts1=explode("-", $beginDate);
   $date_parts2=explode("-", $endDate);

   $start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
   $end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
   $diff = $end_date - $start_date;
   echo $diff;
   $years = floor($diff / (365.25*60*60*24));
   return $years;
}

echo daysDifference('2011-03-12','2008-03-09');

The $diff gives a number output. When I return $years, am getting 0. What have I done wrong?

Edit
Report

1 Answer

-4

If you want the number of years between two dates, why not just use the following :

function yearsDifference($endDate, $beginDate)
{
   $date_parts1=explode("-", $beginDate);
   $date_parts2=explode("-", $endDate);
   return $date_parts2[0] - $date_parts1[0];
}

echo yearsDifference('2011-03-12','2008-03-09');

Which, in this case, will get you :

3
answered 2011-03-22T05:24:42.453

Your Answer