[英]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.