用PHP创建调整后的年龄

sta*_*ets 0 php time

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,这打破了我的大脑.有人介意检查我吗?干杯.

Bai*_*ker 5

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;
}
Run Code Online (Sandbox Code Playgroud)

基本上它是什么,它创建了当年4月31日的DateTime对象,然后减去该人出生的日期.这会生成一个DateInterval,从中检索并返回年份.