-1

I need to get the age of a person. In case of an infant <= 7 days the output should be done in days. If the person is > 2 months and < 1 year the output should be months.

Here I got the problem, that some months are 31 other 30 or 28 days, so my solution isn't exact. Same problem for the else-case: Years with 366 days are ignored by my attempt, so the age isn't calculated correctly.

$timestamp = time();
$birthday_timestamp = mktime(0, 0, 0, $month, $day, $year);
$difference = $timestamp - $birthday_timestamp;

if ($difference < 1209600) return $output = ($difference / 86400)." days";
elseif ($difference < 5184000) return $output = ($difference / 86400 * 7). " weeks";
elseif ($difference < 31536000) return $output = ($difference / 86400 * 30). " months";
else return $output = ($difference / 86400 * 365). " years";
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • possible duplicate of [PHP calculate age](http://stackoverflow.com/questions/3776682/php-calculate-age) –  Jan 12 '15 at 22:55
  • My problem is that I need different output for different ages (infant, toddler etc.). So I don't see the answer in the linked post. – user3142695 Jan 12 '15 at 23:09

1 Answers1

0

Don't try to calculate dates and differences between dates yourself. PHP has some very nice classes to do that for you.

$now = new DateTime();
$birthDay = new DateTime('1985-05-24');

$diff = $birthDay->diff($now);

var_dump($diff);

This is safe and takes into account leap years and other strange things that will occur when calculating with dates.

$diff will be a DateInterval and contains properties like $y, $m and $d.

Arjan
  • 9,784
  • 1
  • 31
  • 41