php PHP计算年龄
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3776682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP calculate age
提问by stef
I'm looking for a way to calculate the age of a person, given their DOB in the format dd/mm/yyyy.
我正在寻找一种方法来计算一个人的年龄,给定他们的 DOB,格式为 dd/mm/yyyy。
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.
我正在使用以下功能,该功能可以正常工作几个月,直到某种故障导致 while 循环永远不会结束并使整个站点停止。由于每天有近 100,000 个 DOB 多次执行此功能,因此很难确定导致这种情况的原因。
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;
EDIT: this function seems to work OK some of the time, but returns "40" for a DOB of 14/09/1986
编辑:这个函数在某些时候似乎可以正常工作,但对于 1986 年 9 月 14 日的 DOB 返回“40”
return floor((time() - strtotime($birthdayDate))/31556926);
回答by Sudhir Bastakoti
This works fine.
这工作正常。
<?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;
?>
回答by salathe
$tz = new DateTimeZone('Europe/Brussels');
$age = DateTime::createFromFormat('d/m/Y', '12/02/1973', $tz)
->diff(new DateTime('now', $tz))
->y;
As of PHP 5.3.0 you can use the handy DateTime::createFromFormat
to ensure that your date does not get mistaken for m/d/Y
format and the DateInterval
class (via DateTime::diff
) to get the number of years between now and the target date.
从 PHP 5.3.0 开始,您可以使用方便的方法DateTime::createFromFormat
来确保您的日期不会被误认为是m/d/Y
格式,并且可以使用DateInterval
类 (via DateTime::diff
) 来获取从现在到目标日期之间的年数。
回答by Wernight
$date = new DateTime($bithdayDate);
$now = new DateTime();
$interval = $now->diff($date);
return $interval->y;
回答by Andrey Korchak
I use Date/Time for this:
我为此使用日期/时间:
$age = date_diff(date_create($bdate), date_create('now'))->y;
回答by Mike
Simple method for calculating Age from dob:
从dob计算年龄的简单方法:
$_age = floor((time() - strtotime('1986-09-16')) / 31556926);
31556926
is the number of seconds in a year.
31556926
是一年中的秒数。
回答by matinict
// Age Calculator
// 年龄计算器
function getAge($dob,$condate){
$birthdate = new DateTime(date("Y-m-d", strtotime(implode('-', array_reverse(explode('/', $dob))))));
$today= new DateTime(date("Y-m-d", strtotime(implode('-', array_reverse(explode('/', $condate))))));
$age = $birthdate->diff($today)->y;
return $age;
}
$dob='06/06/1996'; //date of Birth
$condate='07/02/16'; //Certain fix Date of Age
echo getAge($dob,$condate);
回答by Travis Mark Chong
I find this works and is simple.
我发现这很有效而且很简单。
Subtract from 1970 because strtotime calculates time from 1970-01-01 (http://php.net/manual/en/function.strtotime.php)
从 1970 减去因为 strtotime 从 1970-01-01 ( http://php.net/manual/en/function.strtotime.php)计算时间
function getAge($date) {
return intval(date('Y', time() - strtotime($date))) - 1970;
}
Results:
结果:
Current Time: 2015-10-22 10:04:23
getAge('2005-10-22') // => 10
getAge('1997-10-22 10:06:52') // one 1s before => 17
getAge('1997-10-22 10:06:50') // one 1s after => 18
getAge('1985-02-04') // => 30
getAge('1920-02-29') // => 95
回答by Broshi
You can use the Carbon
library, which is an API extension for DateTime.
您可以使用Carbon
库,它是 DateTime 的 API 扩展。
You can:
你可以:
function calculate_age($date) {
$date = new \Carbon\Carbon($date);
return (int) $date->diffInYears();
}
or:
或者:
$age = (new \Carbon\Carbon($date))->age;
回答by SpYk3HH
Figured I'd throw this on here since this seems to be most popular form of this question.
我想我会把它扔在这里,因为这似乎是这个问题最受欢迎的形式。
I ran a 100 year comparison on 3 of the most popular types of age funcs i could find for PHP and posted my results (as well as the functions) to my blog.
我对我能找到的 3 种最流行的 PHP 年龄函数进行了 100 年的比较,并将我的结果(以及函数)发布到了我的博客。
As you can see there, all 3 funcs preform well with just a slight difference on the 2nd function. My suggestion based on my results is to use the 3rd function unless you want to do something specific on a person's birthday, in which case the 1st function provides a simple way to do exactly that.
正如您在那里看到的,所有 3 个 funcs 都很好地执行,只是在第二个函数上略有不同。基于我的结果,我的建议是使用第三个函数,除非您想在某人的生日做一些特定的事情,在这种情况下,第一个函数提供了一种简单的方法来做到这一点。
Found small issue with test, and another issue with 2nd method! Update coming to blog soon! For now, I'd take note, 2nd method is still most popular one I find online, and yet still the one I'm finding the most inaccuracies with!
发现测试的小问题,以及第二种方法的另一个问题!即将更新到博客!现在,我要注意,第二种方法仍然是我在网上找到的最受欢迎的方法,但仍然是我发现最不准确的方法!
My suggestions after my 100 year review:
我的 100 年回顾后的建议:
If you want something more elongated so that you can include occasions like birthdays and such:
如果你想要更细长的东西,这样你就可以包括生日之类的场合:
function getAge($date) { // Y-m-d format
$now = explode("-", date('Y-m-d'));
$dob = explode("-", $date);
$dif = $now[0] - $dob[0];
if ($dob[1] > $now[1]) { // birthday month has not hit this year
$dif -= 1;
}
elseif ($dob[1] == $now[1]) { // birthday month is this month, check day
if ($dob[2] > $now[2]) {
$dif -= 1;
}
elseif ($dob[2] == $now[2]) { // Happy Birthday!
$dif = $dif." Happy Birthday!";
};
};
return $dif;
}
getAge('1980-02-29');
Butif you just simply want to know the age and nothing more, then:
但如果你只是想知道年龄而已,那么:
function getAge($date) { // Y-m-d format
return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}
getAge('1980-02-29');
See BLOG
见博客
A key note about the strtotime
method:
关于该strtotime
方法的关键说明:
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the
separator between the various components: if the separator is a slash (/),
then the American m/d/y is assumed; whereas if the separator is a dash (-)
or a dot (.), then the European d-m-y format is assumed. If, however, the
year is given in a two digit format and the separator is a dash (-, the date
string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or
DateTime::createFromFormat() when possible.
回答by hmoyat
If you want to caculate the Age of using the dob, you can also use this function. It uses the DateTime object.
如果你想计算使用dob的年龄,也可以使用这个函数。它使用 DateTime 对象。
function calcutateAge($dob){
$dob = date("Y-m-d",strtotime($dob));
$dobObject = new DateTime($dob);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
return $diff->y;
}