【问题标题】:Getting wrong results calculating age with PHP使用 PHP 计算年龄时得到错误的结果
【发布时间】:2013-09-06 14:53:29
【问题描述】:

我无法让我的脚本计算年龄,我从数据库中提取了生日,我希望脚本将该日期识别为生日。它从我的数据库中出来的格式是年/月/日

echo "Player Name: ".$row['FirstName']." ".$row['LastName']."<br>";
echo "Position: ".$row['Position']."<br>";
echo "Height: ".$row['Height']."<br>";
 echo "Weight: ".$row['Weight']."<br>";
 echo "Birthdate: ".$row['DOB']."<br>";
 echo //date in yyyy.mm.dd format; or it can be in other formats as well
     $DOB = "2001.12.31";
     //explode the date to get year, month and day
     $DOB = explode(".", $DOB);
     //get age from date or DOB
     $age = (date("md", date("U", mktime(0, 0, 0, $DOB[0], $DOB[1], $DOB[2]))) >   date("md") ? ((date("Y")-$DOB[2])-1):(date("Y")-$DOB[2]));
echo "Age is:".$age."<br>";
echo "CNGHL Team: ".$row['CNGHLRights']."<br>";
echo "NHL Team: ".$row['Team']."<br>";
echo "Draft Year: ".$row['CNDraftYR']."<br>";   
echo "Draft Position: ".$row['CNDraftPOS']."<br>";
echo "Drafted By: ".$row['CNDraftTEAM']."<br>";
echo "<img src=\"http://www.cnghl.info/cnghldb/images/".$iPlayerID.".jpg\">";

它从脚本 2001.12.31 中的日期中提取,而不是脚本从带有 DOB 的数据库中提取的日期。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

标签: php mysql sql


【解决方案1】:

嗨,布莱恩·J·柯克。我认为这些链接可能会对您有所帮助。

age calculation in php

current age calculation in php

【讨论】:

    【解决方案2】:
     $date1 = "2012-09-13";
     $date2 = date("Y-m-d");
            $diff = abs(strtotime($date2) - strtotime($date1));
            $years = floor($diff / (365*60*60*24));
            $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
            $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
            $finaldate = ($years*365)+ ($months*30)+$days;
            $finalyear = floor($finaldate/365);
    

    【讨论】:

    • 会考虑闰年吗?
    • 并且由于 abs 调用,它会错误地计算未来出生的球员的年龄 :)
    • 你可以绑定用户不要在日历中选择未来的日期
    • @Prasannjit 但这会使 abs 调用变得不必要。现在,abs 调用所做的只是通过给出可能被误解为无效输入的合理结果来隐藏潜在的错误。
    【解决方案3】:
    <?php
    $DOB = "31.12.2001"; //dd.mm.yyyy
    $user_date = new DateTime($DOB);
    $curr_date = new DateTime(); 
    $age_cal = $curr_date->diff($user_date);
    echo $age_cal->y;
    ?>
    

    【讨论】:

      【解决方案4】:

      使用这个

      <?php
      
           $birthDate = "2001.12.31";
           //explode the date to get month, day and year
           $birthDate = explode(".", $birthDate);
           //get age from date or birthdate
           $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[2], $birthDate[1],  $birthDate[0]))) > date("md") ? ((date("Y")-$birthDate[0])-1):(date("Y")-$birthDate[0]));
           echo "Age is:".$age;
      

      【讨论】:

        猜你喜欢
        • 2012-03-26
        • 2020-12-28
        • 2011-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多