gpt4 book ai didi

PHP计算年龄

转载 作者:IT老高 更新时间:2023-10-28 11:43:18 24 4
gpt4 key购买 nike

我正在寻找一种方法来计算一个人的年龄,给定他们的出生日期,格式为 dd/mm/yyyy。

我一直在使用以下函数,该函数运行了几个月,直到某种故障导致 while 循环永远不会结束,并使整个站点停止运行。由于每天有近 100,000 个 DOB 多次使用此功能,因此很难确定是什么原因造成的。

有没有更可靠的计算年龄的方法?

//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));
$tdate = time();

$age = 0;
while( $tdate > $dob = strtotime('+1 year', $dob))
{
++$age;
}
return $age;

编辑:这个函数在某些时候似乎可以正常工作,但是对于 1986 年 9 月 14 日的 DOB 返回“40”

return floor((time() - strtotime($birthdayDate))/31556926);

最佳答案

这很好用。

<?php
//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = "12/17/1983";
//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计算年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3776682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com