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, \$bdate, \$bdate);
\$end_date=gregoriantojd(\$edate, \$edate, \$edate);
return \$end_date - \$start_date;
}

Note: Date Format should be MM/DD/YYY

How to use this function?

\$d1=11/05/1980
\$d2=7/31/2008
echo "difffrance between \$d2 and \$d1 is ".dateDiff(\$d2,\$d1);

How to calculate age in years

\$dob="08/12/1975";
\$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 ";

A Mechanical engineer by education and web developer by passion and profession. He lives in Lucknow, India. Currently earning his livings by hitting keyboad. ;)

Join the Conversation

1. 1 Comment

1. Rajesh sahu says:

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