Calculate years from date

浪子不回头ぞ 提交于 2019-11-29 01:32:58
Paolo Bergantino

Your code doesn't work because the function is not returning anything to print.

As far as algorithms go, how about this:

function getAge($then) {
    $then_ts = strtotime($then);
    $then_year = date('Y', $then_ts);
    $age = date('Y') - $then_year;
    if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
    return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet

This is the same algorithm (just in PHP) as the accepted answer in this question.

A shorter way of doing it:

function getAge($then) {
    $then = date('Ymd', strtotime($then));
    $diff = date('Ymd') - $then;
    return substr($diff, 0, -4);
}

An alternative way to do this is with PHP's DateTime class which is new as of PHP 5.2:

$birthdate = new DateTime("1986-06-18");
$today     = new DateTime();
$interval  = $today->diff($birthdate);
echo $interval->format('%y years');

See it in action

You need to return $yearDiff, I think.

A single line function can work here

function calculateAge($dob) {
    return floor((time() - strtotime($dob)) / 31556926);
}

To calculate Age

 $age = calculateAge('1990-07-10');
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!