问题描述:

This is the code I'm currently using, but it's not working. Geboortedatum means day of birth in Dutch.

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;

?>

网友答案:

No need for PHP calculation. MySQL might do it by itself (with help of TIMESTAMPDIFF()):

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

If you store your date in format, that differs form MySQL Date format (i.e. not in YYYY-mm-dd format), then you may try to format it with STR_TO_DATE() function.

网友答案:

This works fine,but your date should be in this format : 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;
    ?>

DEMO

网友答案:

Here's an approach if you want a breakdown by years, months, and Days:

$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.;
相关阅读:
Top