Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to calculate person age in months

Tags:

function

php

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

like image 245
Awan Avatar asked Jul 24 '10 09:07

Awan


2 Answers

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.

like image 180
Daniel Egeberg Avatar answered Sep 17 '22 18:09

Daniel Egeberg


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

var_dump($months);

Something along these lines?

like image 45
kander Avatar answered Sep 17 '22 18:09

kander