[英]Calculate Age for PHP 5.2
我正在嘗試從一個ExpressionEngine網站上的一個人的出生日期算起他的年齡。 以下代碼可在我的本地測試站點上運行,但是服務器使用的是PHP(5.2.17)的舊版本,所以我遇到了錯誤。 有人可以建議我代替使用什么代碼嗎?
{exp:channel:entries channel='zoo_visitor'}
<?php
$dob = new DateTime('{member_birthday format='%Y-%m-%d'}');
$now = new DateTime('now');
// This returns a DateInterval object.
$age = $now->diff($dob);
// You can output the date difference however you choose.
echo 'This person is ' .$age->format('%y') .' years old.';
?>
{/exp:channel:entries}
您當前的代碼無法正常工作,因為PHP 5.3.0中引入了DateTime::diff
。
通常,日期算術非常棘手,因為您必須考慮時區,DST和leap年,但是對於像計算“全年”差異這樣的簡單任務,您可以輕松地做到這一點。
這個想法是,結果等於結束日期的年份減去開始日期的年份,並且如果開始日期的月份/日期早於結束日期,則應該從中減去1。 編碼:
$dob = new DateTime('24 June 1940');
$now = new DateTime('now');
echo year_diff($now, $dob);
function year_diff($date1, $date2) {
list($year1, $dayOfYear1) = explode(' ', $date1->format('Y z'));
list($year2, $dayOfYear2) = explode(' ', $date2->format('Y z'));
return $year1 - $year2 - ($dayOfYear1 < $dayOfYear2);
}
看到它在行動 。 請注意,在與生日指定的同一天,結果如何增加1。
$dob = strtotime('{member_birthday format='%Y-%m-%d'}');
$now = time();
echo 'This person is ' . (1970 - date('Y', ($now - $dob))) .' years old.';
經過大量搜索,我找到了答案:
<?php
//date in mm/dd/yyyy format
$birthDate = "{member_birthday format='%m/%d/%Y'}";
//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;
?>
在某些特殊情況下,僅使用一年中的某一天的計算會減少:它們顯示2012-02-29和2011-03-01為1年,而應該為0年(分別為11個月和28天)。 考慮leap年的可能解決方案是:
<?php
function calculateAge(DateTime $birthDate, DateTime $now = null) {
if ($now == null) {
$now = new DateTime;
}
$age = $now->format('Y') - $birthDate->format('Y');
$dm = $now->format('m') - $birthDate->format('m');
$dd = $now->format('d') - $birthDate->format('d');
if ($dm < 0 || ($dm == 0 && $dd < 0)) {
$age--;
}
return $age;
}
echo calculateAge(new DateTime('2011-04-01'), new DateTime('2012-03-29'));
不過,user579984的解決方案也有效。
$birthday = '1983-03-25';
$cm = date('Y', strtotime($birthday));
$cd = date('Y', strtotime('now'));
$res = $cd - $cm;
if (date('m', strtotime($birthday)) > date('m', strtotime('now')))
$res--;
else if ((date('m', strtotime($birthday)) == date('m', strtotime('now'))) &&
(date('d', strtotime($birthday)) > date('d', strtotime('now'))))
$res--;
echo $res;
我一直在使用它,它永遠不會讓我失望。 YYYYMMDD
是該人的生日。
$age = floor((date('Ymd') - 'YYYYMMDD') / 10000);
如果您想更嚴格一點,可以使用intval
函數將日期轉換為整數,或者在日期之前加上(int)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.