本文介绍了使用我的数据库中的数据计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我目前使用的代码,但它不工作。 Geboortedatum是指荷兰语的出生日。
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;
?>
推荐答案
不需要PHP计算。 MySQL可以自己做(借助):
No need for PHP calculation. MySQL might do it by itself (with help of TIMESTAMPDIFF()
):
SELECT TIMESTAMPDIFF(YEAR, `Geboortedatum`, NOW()) as `age` FROM `Personen`;
如果您以格式存储日期,形式MySQL日期格式(即不在 YYYY-mm-dd
格式),那么您可以尝试使用 STR_TO_DATE()
a>函数。
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.
这篇关于使用我的数据库中的数据计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!