I recently needed to calculate age in months ranging from prenatal to 5 years old (60+ months).
Neither of the answers above worked for me.
The first one I tried, which is basically a 1 liner for deceze's answer
$bdate = strtotime('2011-11-04');
$edate = strtotime('2011-12-03');
$age = ((date('Y',$edate) - date('Y',$bdate)) * 12) + (date('m',$edate) - date('m',$bdate));
. . .
This fails with the set dates, obviously the answer should be 0 as the month mark (2011-12-04) hasn't been reached yet, how ever the code returns 1.
The second method I tried, using Adam's code
$bdate = strtotime('2011-01-03');
$edate = strtotime('2011-02-03');
$age = 0;
while (strtotime('+1 MONTH', $bdate) < $edate) {
$age++;
$bdate = strtotime('+1 MONTH', $bdate);
}
. . .
This fails and says 0 months, when it should be 1.
What did work for me, is a little expansion of this code. What I used is the following:
$bdate = strtotime('2011-11-04');
$edate = strtotime('2012-01-04');
$age = 0;
if($edate < $bdate) {
//prenatal
$age = -1;
} else {
//born, count months.
while($bdate < $edate) {
$age++;
$bdate = strtotime('+1 MONTH', $bdate);
if ($bdate > $edate) {
$age--;
}
}
}