我想我会把它放在这里,因为这似乎是这个问题最流行的形式。
我对我能找到的 3 种最流行的 PHP 年龄函数类型进行了 100 年比较,并将我的结果(以及函数)发布到 my blog。
如您所见there,所有 3 个功能都表现良好,仅在第 2 个功能上略有不同。根据我的结果,我的建议是使用第三个函数,除非你想在一个人的生日做一些特定的事情,在这种情况下,第一个函数提供了一种简单的方法来做到这一点。
发现测试的小问题,以及第二种方法的另一个问题!更新即将来到博客!现在,我要注意,第二种方法仍然是我在网上找到的最流行的一种,但仍然是我发现最不准确的一种!
我的 100 年回顾后的建议:
如果你想要一些更细长的东西,以便你可以包括生日等场合:
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');
但是如果你只是想知道年龄而已,那么:
function getAge($date) { // Y-m-d format
return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}
getAge('1980-02-29');
See BLOG
关于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.