计算给定生日的人的年龄

Calculating the age of a person with given birthday

我需要获取一个人的年龄。如果婴儿 <= 7 天,则输出应以天为单位。如果此人 > 2 个月且 < 1 年,则输出应为月数。

这里我遇到了问题,有些月份是 31 天,其他月份是 30 天或 28 天,所以我的解决方案并不准确。对于 else-case 也有同样的问题:我的尝试忽略了 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.

等属性