使用PHP计算年龄得到错误的结果

时间:2013-09-06 05:16:15

标签: php mysql sql

我无法让我的脚本计算年龄,我从数据库中提取了生日,我希望脚本能够将该日期作为生日来重现。它来自我的数据库的格式是年/月/日我通过查找如何执行此操作的脚本继续获得奇怪的结果。

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的数据库中提取的日期。

非常感谢任何帮助。

谢谢!

4 个答案:

答案 0 :(得分:3)

嗨,Brian J Kirk。我认为这些链接可能会对您有所帮助。

age calculation in php

current age calculation in php

答案 1 :(得分: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);

答案 2 :(得分:1)

<?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;
?>

答案 3 :(得分:0)

使用此

<?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;