我正在尝试根据 DOB 计算最接近的年龄,但我不知道该怎么做。我尝试了一些估计的方法,但这还不够好。我们需要计算从今天到下一个生日的天数,无论是在今年还是明年。并再次计算从今天到上一个生日的天数,无论是今年还是去年。
有什么建议么?
我正在尝试根据 DOB 计算最接近的年龄,但我不知道该怎么做。我尝试了一些估计的方法,但这还不够好。我们需要计算从今天到下一个生日的天数,无论是在今年还是明年。并再次计算从今天到上一个生日的天数,无论是今年还是去年。
有什么建议么?
如果我理解正确,您想“圆”年龄吗?那么沿着这些思路怎么样:
$dob = new DateTime($birthday);
$diff = $dob->diff(new DateTime);
if ($diff->format('%m') > 6) {
echo 'Age: ' . ($diff->format('%y') + 1);
} else {
echo 'Age: ' . $diff->format('%y');
}
我认为这就是您想要的……当然,您可以将一个人的年龄精确到当天,然后将其向上或向下舍入到最接近的年份……这可能是我应该做的。
这是相当蛮力的,所以我相信你可以做得更好,但它的作用是检查今年、明年和去年生日之前的天数(我分别检查了这三个而不是从 365 中减去,因为 date()照顾闰年,我不想)。然后它会根据其中最接近的生日来计算年龄。
<?php
$bday = "September 3, 1990";
// Output is 21 on 2011-08-27 for 1990-09-03
// Check the times until this, next, and last year's bdays
$time_until = strtotime(date('M j', strtotime($bday))) - time();
$this_year = abs($time_until);
$time_until = strtotime(date('M j', strtotime($bday)).' +1 year') - time();
$next_year = abs($time_until);
$time_until = strtotime(date('M j', strtotime($bday)).' -1 year') - time();
$last_year = abs($time_until);
$years = array($this_year, $next_year, $last_year);
// Calculate age based on closest bday
if (min($years) == $this_year) {
$age = date('Y', time()) - date('Y', strtotime($bday));
}
if (min($years) == $next_year) {
$age = date('Y', strtotime('+1 year')) - date('Y', strtotime($bday));
}
if (min($years) == $last_year) {
$age = date('Y', strtotime('-1 year')) - date('Y', strtotime($bday));
}
echo "You are $age years old.";
?>
编辑:删除了计算中不必要date()
的 s $time_until
。
编辑:重写以使用DateInterval
这应该为您解决问题...
$birthday = new DateTime('1990-09-03');
$today = new DateTime();
$diff = $birthday->diff($today, TRUE);
$age = $diff->format('%Y');
$next_birthday = $birthday->modify('+'. $age + 1 . ' years');
$halfway_to_bday = $next_birthday->sub(DateInterval::createFromDateString('182 days 12 hours'));
if($today >= $halfway_to_bday)
{
$age++;
}
echo $age;