简体   繁体   English

使用PHP从Mysql数据库计算确切年龄

[英]Calculate Exact Age From Mysql Database Using PHP

I am facing a problem while printing exact age using php. 我在使用php打印确切年龄时遇到问题。 The years of the age are printing exactly but when it comes to months and days they often goes to negative values. 年龄的岁月正好在打印,但是涉及到几个月和几天,它们通常会变为负值。

Here is the snippet of the code and full code is here . 这是代码段,完整的代码在这里

$ag = date('Y') - substr($row11['dob'],6);
        $mn = date('m') - substr($row11['dob'],3,2);
        $dy = date('d') - substr($row11['dob'],0,2);

Your age calculation method is not Right, bcz by separation from today's year to birth year is fine but when it come to month and date it will gives negative value, direct separation will not work for age calculation. 您的年龄计算方法不正确,通过从今天的年份到出生年份的分隔进行bcz很好,但是当到达月份和日期时它将给出负值,因此直接分隔不适用于年龄计算。 Use following code. 使用以下代码。

    function ageCalculator($dob){
    if(!empty($dob)){
        $birthdate = new DateTime($dob);
        $today   = new DateTime('today');
        $ag = $birthdate->diff($today)->y;
        $mn = $birthdate->diff($today)->m;
        $dy = $birthdate->diff($today)->d;
        return "$ag Years $mn Months $dy Days";
    }else{
        return 0;
    }
}

$row11 = array('dob'=>'02-01-1995');
echo ageCalculator($row11['dob']);

//OUTPUT

22 Years 9 Months 20 Days

Here you can find the file 在这里您可以找到文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM