The calculation of an age (given a date of birth) isn’t a trivial task in a PHP world. Although I guess hope that there are PHP coders who are up to such a job, it seems that they are rather shy. In any case, my search resulted in nothing but amazingly inaccurate, wrong and/or long winded solutions. It’s about time that somebody saves our honor and … alright, I’ll do it.
The function takes a year, month and day of birth as single arguments in the said order. It returns full years.
<?php
/**
* function getAge
* Copyright (C) 2006 Dao Gottwald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact information:
* Dao Gottwald <dao at design-noir.de>
*
* @version 1.0
*/
function getAge($y, $m, $d) {
return date('Y') - $y - (date('n') < (ltrim($m,'0') + (date('j') < ltrim($d,'0'))));
}
?>
That’s it? – Yep, that’s it. It wasn’t so bad, was it?
Now some test cases, let’s hope it works.
<?php
require_once 'getAge.php';
function test($y, $m, $d) {
echo str_pad($y.'-'.$m.'-'.$d, 12), getAge($y, $m, $d), "\n";
}
test(1985, 10, 27);
test(2000, 1, 1);
test('2000', '01', '01');
test(2000, 12, 31);
test(2000, date('m'), 1);
test(2000, date('m'), date('d'));
test(2000, date('m', strtotime('+1 day')), date('d', strtotime('+1 day')));
test(-38000, 1, 1);
test(2100, 1, 1);
test(2100, 12, 31);
echo "\n";
for ($i = 0; $i <= 30; $i += 3) {
$t = strtotime('-'.$i.'00 days');
test(date('Y', $t), date('m', $t), date('d', $t));
}
?>