简体   繁体   English

计算PHP 5.2的年龄

[英]Calculate Age for PHP 5.2

I am trying to calculate a person's age from their date of birth on an ExpressionEngine site. 我正在尝试从一个ExpressionEngine网站上的一个人的出生日期算起他的年龄。 The following code works on my local test site but the server is using an older version of PHP (5.2.17) so I amgetting errors. 以下代码可在我的本地测试站点上运行,但是服务器使用的是PHP(5.2.17)的旧版本,所以我遇到了错误。 Could someone suggest what code I would need to use instead? 有人可以建议我代替使用什么代码吗?

{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}

Your current code won't work because DateTime::diff was introduced in PHP 5.3.0. 您当前的代码无法正常工作,因为PHP 5.3.0中引入了DateTime::diff

Normally date arithmetic is quite tricky because you have to take into account timezones, DST and leap years, but for a task as simple as calculating a "whole year" difference you can do it quite easily. 通常,日期算术非常棘手,因为您必须考虑时区,DST和leap年,但是对于像计算“全年”差异这样的简单任务,您可以轻松地做到这一点。

The idea is that the result is equal to the end date's year minus the start date's year, and if the start date's month/day is earlier inside the year than the end date's you should subtract 1 from that. 这个想法是,结果等于结束日期的年份减去开始日期的年份,并且如果开始日期的月份/日期早于结束日期,则应该从中减去1。 The code: 编码:

$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);
}

See it in action . 看到它在行动 Note how the result increases by 1 on the exact same day as specified for the birthday. 请注意,在与生日指定的同一天,结果如何增加1。

$dob = strtotime('{member_birthday format='%Y-%m-%d'}');
$now = time();
echo 'This person is ' . (1970 - date('Y', ($now - $dob))) .' years old.';

You can use the diff only above PHP 5.3 您只能在PHP 5.3以上使用diff

You can try with modify, it works on 5.2 您可以尝试进行修改,它适用于5.2

$age = $now->modify('-' . $dob->format('Y') . 'year');

After much search I have found the answer: 经过大量搜索,我找到了答案:

<?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;
?>   

The calculations which only use day of year are off by one in some corner cases: They show 1 year for 2012-02-29 and 2011-03-01, while this should be 0 years (and 11 months and 28 days). 在某些特殊情况下,仅使用一年中的某一天的计算会减少:它们显示2012-02-29和2011-03-01为1年,而应该为0年(分别为11个月和28天)。 A possible solution which takes into account leap years is: 考虑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's solution works, too, though. 不过,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;

I've been using this and it's never let me down. 我一直在使用它,它永远不会让我失望。 YYYYMMDD being the person's birthday. YYYYMMDD是该人的生日。

$age = floor((date('Ymd') - 'YYYYMMDD') / 10000);

If you want to be more strict you could convert the dates to integers using the intval function or preceding the dates with (int) . 如果您想更严格一点,可以使用intval函数将日期转换为整数,或者在日期之前加上(int)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM