使用PHP创建调整年龄



我正在用PHP构建一个注册系统,需要创建一个函数,该函数接受出生日期(作为时间戳)并在(4月31日)返回年龄。我现在拥有的是:

<?php
function get_adj_age($dob)
{
    $age = (time()-$dob);
    $today = strtotime(date('F d', time()));
    $diff = ($cutoff - $today);
    $adj_age = floor(($age+$diff)/31556926);
    return $adj_age;
}

出于某种原因,这让我伤透了脑筋。有人介意帮我查一下吗?干杯

function adjustedAge($dob, $adjustTo = 'April 31') { // DOB can be of any format accepted by strtotime()
    return ((new DateTime($adjustTo.', '.date('Y')))->diff(new DateTime($dob)))->y;
}

从本质上讲,它为当年的4月31日创建了一个DateTime对象,然后减去这个人的出生日期。这将产生一个DateInterval,从中检索并返回年份。

这很简单。首先获取当前时间并将其存储在变量中。然后得到以毫秒为单位的年龄(考虑到1969年之前的时间戳是负的,因此是三元运算符)。年龄现在以毫秒为单位,所以用它除以一年中的毫秒数(60*60*24*365)

function getAge($birth){
    $t = time();
    $age = ($birth < 0) ? ( $t + ($birth * -1) ) : $t - $birth;
    return floor($age/31536000);
}

要获取特定日期的年龄,只需为所需日期创建一个时间戳,而不是使用当前时间。

$t = mktime(0, 0, 0, 4, 31, 2012); // <-- April 31st, 2012

相关内容

最新更新