Calculating Difference Between Two Dates Using PHP
July 12th, 2009
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);
$eedate=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?
$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.";
And if you are using PHP, why did you accept that date is going to be string in some stupid format and not in seconds since the Epoch???
And why did you assume that a year has always 365 days???
Even my little daughter knows that there are leap years!!!