views:

77

answers:

3

I have searched for this but did not find a perfect function in php. I want to get a php function that calculate person age only in months.

For example:

less then one month old.
5 months old.
340 months old.

Thanks

A: 

If you want years to months, where the person inputs their ages as $years

$month = $years*12;

If you want months to years, where the person inputs their age as $months

$year = $months/12
ina
This is not completely accurate, considering the fact that the months aren't distributed evenly (28, 29, 30, 31 days per month).
kander
Also, if a person is born in January and now is July, the computation would be wrong by 7 months.
klez
not if you assume $years can be input as a decimal.. e.g. 1.5 years etc
ina
+4  A: 

Using PHP's DateInterval (available from 5.3.0), that's pretty easy:

$birthday = new DateTime('1990-10-13');
$diff = $birthday->diff(new DateTime());
$months = $diff->format('%m') + 12 * $diff->format('%y');

Now $months will contain the number of months I've lived.

Daniel Egeberg
Is there a specific reason to use $diff->format() over accessing the y and m properties of the DateInterval directly?
kander
Nope. You can do that as well if you wish.
Daniel Egeberg
I don't see any mention of those properties in the documentation. Using undocumented features is generally a bad idea as they are more likely to change in the future.
Ruben
Daniel Egeberg
+1  A: 
$birthday = new DateTime("June 21st 1986");
$diff = $birthday->diff(new DateTime());
$months = ($diff->y * 12) + $diff->m;

var_dump($months);

Something along these lines?

kander