计算给定生日的人的年龄


Calculating the age of a person with given birthday

我需要得到一个人的年龄。如果是婴儿<= 7天,输出应在天内完成。如果该人> 2 个月且<1 年,则输出应为月。

在这里,我遇到了问题,有些月份是另外 31 天或 30 天或 28 天,所以我的解决方案并不准确。对于其他情况,同样的问题:我的尝试忽略了 366 天的年份,因此年龄计算不正确。

$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";

不要尝试自己计算日期和日期之间的差异。PHP 有一些非常好的类来为你做到这一点。

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

这是安全的,并考虑到闰年和计算日期时会发生的其他奇怪事情。

$diff将是一个DateInterval,包含$y$m$d等属性。