DateTime Diff having inconsistencies in Months

Having a problem with difference in months, function below returns the age with month

function ageMonths($dob)
{
    //new date time $dob must be Y-m-d format
    $dobObject = DateTime::createFromFormat('Y-m-d',$dob);

    //current date
    $nowObject = new DateTime();

    //difference
    $diff = $nowObject->diff($dobObject);
    return $diff->y.'.'.$diff->m;
}

problem is i am having inconsistencies in months some are exact some are not, please look at the sample below

5.5 - 2008-10-03 correct
8.2 - 2005-12-27 must be 8.3
4.5 - 2009-09-24 must be 4.6
6.7 - 2007-07-14 must be 6.8
6.7 - 2007-07-17 must be 6.8
6.5 - 2007-09-28 must be 6.6
7.1 - 2007-01-17 must be 7.2
7.1 - 2007-02-10 correct
6.3 - 2007-11-16 must be 6.4
7.1 - 2007-02-10 correct
6.3 - 2007-11-16 must be 6.4
6.10 - 2007-05-08 correct

I cannot find what is wrong, any ideas?

Answers


There is no rounding going on, it's just that your notion of "months difference" is not the same as the one used by DateInterval.

Subtracting two DateTime values imbues the resulting DateInterval with a "months" value equal to the number of whole (in the calendar sense) months of difference between the dates. For example, in calendar terms 2013-03-11 is zero months away from 2013-04-01 (2013-04-11 would be one month away).

What you want is not months of difference calendar-wise, but the arithmetic difference of month indexes. For example, 2013-03-11 has a month difference of 1 from 2013-04-01 (because 4 - 3 = 1).

So, get your desired result this way:

$dobObject = DateTime::createFromFormat('Y-m-d',$dob);
$nowObject = new DateTime();

return $dobObject->format('n') - $nowObject->format('n'); // might be negative

See the difference live.


2008-10-03 -> Y - m - d here m represents with leading zeros 01 through 12. 2008-10-03 -> Y - n - d here n represents without leading zeros 1 through 12.

use n for getting exact month for calculating age. cheers


Need Your Help

Getting 1 record even a day includes 2 different record

sql sql-server-2008

There is a table which shows employee's daily program.

My DIV width is not expanding with the size of its children

css html width

I have a parent div (nav) that is 1000px. Within that there is a child div (nav-drop-panel), and within that one another child (drop-panel-col). Basically, the drop-panel-col is a list of links in