1

这是我目前正在使用的代码,但它不起作用。Geboortedatum 在荷兰语中是生日的意思。

mysql_connect('xxx', 'xxx', 'xxx');

mysql_select_db('xxx'); 

$result = mysql_query("select Geboortedatum from Personen");

while ($row = mysql_fetch_array($result)){

$datum= $row["Geboortedatum"];
}

     //date in mm/dd/yyyy format; or it can be in other formats as well
     $birthDate = $datum;
echo $birthDate;
     //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[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));
     echo "Age is:".$age;
?>
4

3 回答 3

5

无需 PHP 计算。MySQL 可以自己完成(在 的帮助下TIMESTAMPDIFF()):

SELECT TIMESTAMPDIFF(YEAR, `Geboortedatum`, NOW()) as `age` FROM `Personen`;

如果您以不同于 MySQL 日期格式(即不是YYYY-mm-dd格式)的格式存储日期,那么您可以尝试使用STR_TO_DATE()函数对其进行格式化。

于 2013-09-15T15:51:56.377 回答
0

如果您想按年、月和日细分,可以使用以下方法:

$secondsInAYear     = 31536000;
$secondsInAMonth    =  2635200; //Using the average (30.5) days in a month.
$secondsInADay      =    86400;


echo $datum;
$birthDate = strtotime($datum);

$ageInSeconds   = time() - $birthDate;

$ageInYears = floor( $ageInSeconds / $secondsInAYear );
$ageRemainder   = ( $ageInSeconds % $secondsInAYear );          // $a % $b  [ Modulus:  Remainder of $a divided by $b ]     

$ageInMonths    = floor( $ageRemainder / $secondsInAMonth );
$monthsRemainder    = ( $ageRemainder % $secondsInAMonth );

$ageInDays      = floor( $monthsRemainder / $secondsInAMonth );    

echo "Age is:" .$ageInYears ." Years, " .$ageInMonths ." Months, and " .$ageInDays ." Days.;
于 2013-09-15T16:11:13.850 回答
0

这工作正常,但你的日期应该是这种格式:mm/dd/yyyy

<?php
         //date in mm/dd/yyyy format; or it can be in other formats as well
         $birthDate = "02/07/1990";
         //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[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));
         echo "Age is:".$age;
    ?>

演示

于 2013-09-15T15:50:46.627 回答