PHP: Calculating Difference Between Two Dates

Calculation of difference between 2 dates is not an easy task so I m writing a function which do this job easily. This function is useful for calculate age of person by DOB (date of birth) or calculating age of record in databse

function dateDiff($endDate, $beginDate)
$bdate=explode("/", $beginDate);
$edate=explode("/", $endDate);
$start_date=gregoriantojd($bdate[0], $bdate[1], $bdate[2]);
$end_date=gregoriantojd($edate[0], $edate[1], $edate[2]);
return $end_date - $start_date;

Note: Date Format should be MM/DD/YYY

How to use this function?

echo "difffrance between $d2 and $d1 is ".dateDiff($d2,$d1);

How to calculate age in years

$age= round(dateDiff( date("m/d/Y", time()), $dob)/365, 0);
echo "If you were born on " . $dob . ", then today your age is approximately " .$age. " Year.";

Another way for php 5.2 users

php version 5.2 or above has an inbuilt class DateTime to manipulate date and time. we can use this class to get more accurate results

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

Liked It? Get Free updates in your Email

Delivered by feedburner

One thought on “PHP: Calculating Difference Between Two Dates

  1. Rajesh sahu

    variable of $eedate=explode(“/”, $endDate);
    and after explod
    $end_date=gregoriantojd($edate[0], $edate[1], $edate[2]);
    $edate[0],$edate[1],$edate[2] variable name are not same so it is not working due to variable name is not same.

    please correct is.


Leave a Reply

Your email address will not be published. Required fields are marked *