PHP计算年龄 [英] PHP calculate age

查看:47
本文介绍了PHP计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到他们的DOB格式为dd/mm/yyyy,我正在寻找一种计算人的年龄的方法.

I'm looking for a way to calculate the age of a person, given their DOB in the format dd/mm/yyyy.

我正在使用以下功能,该功能在几个月内都工作良好,直到某种故障导致while循环永不结束并将整个站点磨死为止.由于每天有近100,000个DOB多次通过此功能,因此很难确定造成此问题的原因.

I was using the following function which worked fine for several months until some kind of glitch caused the while loop to never end and grind the entire site to a halt. Since there are almost 100,000 DOBs going through this function several times a day, it's hard to pin down what was causing this.

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

Does anyone have a more reliable way of calculating the age?

//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".

this function seems to work OK some of the time, but returns "40" for a DOB of 14/09/1986

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计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆