简体   繁体   中英

PHP: How to calculate person age in months

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

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.

$birthday = new DateTime("June 21st 1986");
$diff = $birthday->diff(new DateTime());
$months = ($diff->y * 12) + $diff->m;

var_dump($months);

Something along these lines?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM