Monday, 3 February 2014

Calculate Age With PHP

Checking dates in PHP can be problematic as PHP primarily concerns itself with date manipulation which revolves around unix timestamps. This is a good thing, mostly. Unix timestamps however, have not concept of leap years, thus it is difficult, though not impossible, to get an accurate date calculation from them. When dates need to be accurate for legal reasons, it is vital that the leap years are considered. Here several solutions are put forward, each nicer than the previous.

With strtotime()

<?php
/*** make sure this is set ***/date_default_timezone_set('Europe/London');
/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge$dob$tdate )
{
        
$age 0;
        while( 
$tdate $dob strtotime('+1 year'$dob))
        {
                ++
$age;
        }
        return 
$age;
}
?>
<?php
/*** a date before 1970 ***/$dob strtotime("april 20 1961");
/*** another date ***/$tdate strtotime("june 2 2009");
/*** show the date ***/echo getAge$dob$tdate );
?>

Using the DateTime Class

The PHP DateTime class allow a little neater code by providing an Object Oriented interface to date functions. By passing a DateInterval object to the DateTime class the DateTime object can be increment 1 year on each iteration until it reaches the target date. The DateTime::add() method requires PHP >= 5.3.
<?php
/*** set the default timezone ***/date_default_timezone_set('Europe/London');
/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge$dob$tdate )
{
        
$dob = new DateTime$dob );
        
$age 0;
        
$now = new DateTime$tdate );
        while( 
$dob->add( new DateInterval('P1Y') ) < $now )
        {
                
$age++;
        }
        return 
$age;
}
?>
<?php
/*** a date before 1970 ***/$dob "April 20 1961";
/*** another date ***/$tdate "21-04-2009";
/*** show the date ***/echo getAge$dob$tdate );
?>

No comments:

Post a Comment