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()
This first method makes use of the PHP strtotime() function and increments a 1 year on each iteration.
<?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;
}?>
EXAMPLE USAGE
<?php
/*** a date before 1970 ***/$dob = strtotime("april 20 1961");
/*** another date ***/$tdate = strtotime("june 2 2009");
/*** show the date ***/echo getAge( $dob, $tdate );
?>
DEMONSTRATION
48
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;
}
?>
EXAMPLE USAGE
<?php
/*** a date before 1970 ***/$dob = "April 20 1961";
/*** another date ***/$tdate = "21-04-2009";
/*** show the date ***/echo getAge( $dob, $tdate );
?>
DEMONSTRATION
48
More DateTime Goodness
Following on with PHP 5.3 and above, the DateTime::diff() method is provided for just this sort of calculation. By using this method, the code is cut down considerably and the calculations done internally.
<?php
/*** dont forget to set this ***/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 )
{
$d1 = new DateTime( $dob );
$d2 = new DateTime($tdate );
$age = $d2->diff( $d1 );
return $age->y;
}
?>
EXAMPLE USAGE
<?php
/*** a date before 1970 ***/$dob = "April 20 1961";
/*** another date ***/$tdate = "21-04-2009";
/*** show the date ***/echo getAge( $dob, $tdate );
?>
48
0 comments:
Post a Comment