简体   繁体   中英

Calculate Age for PHP 5.2

I am trying to calculate a person's age from their date of birth on an ExpressionEngine site. 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. 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.

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.

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

$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

You can try with modify, it works on 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). A possible solution which takes into account leap years is:

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

$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.

$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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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