这是我目前正在使用的代码,但它不起作用。 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;
?>
答案 0 :(得分:5)
无需PHP计算。 MySQL可以自己完成(在TIMESTAMPDIFF()
的帮助下):
SELECT TIMESTAMPDIFF(YEAR, `Geboortedatum`, NOW()) as `age` FROM `Personen`;
如果您以格式存储日期,其格式与MySQL日期格式不同(即不是YYYY-mm-dd
格式),那么您可以尝试使用STR_TO_DATE()
函数对其进行格式化。
答案 1 :(得分: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;
?>
答案 2 :(得分: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.;