[英]Calculate the age using data from my database
这是我当前正在使用的代码,但无法正常工作。 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;
?>
无需PHP计算。 MySQL可能自己做(借助TIMESTAMPDIFF()
):
SELECT TIMESTAMPDIFF(YEAR, `Geboortedatum`, NOW()) as `age` FROM `Personen`;
如果您以与MySQL日期格式不同的格式(即非YYYY-mm-dd
格式)存储日期,则可以尝试使用STR_TO_DATE()
函数对其进行STR_TO_DATE()
。
这可以正常工作,但您的日期应采用以下格式: 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;
?>
如果您想按年,月和天细分,可以采用以下方法:
$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.;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.