These are useful if you're creating something which needs to calculate age on the fly or if you're just plain lazy like me and want to show your age but can't bothered to keep it up to date!
This tutorial assumes you have an understanding of basic php functions like explode, mktime and IF statements.
Here's the code in full, beneath this I'll break it down so you can fully understand what everything does if you are unsure.
$birthDay = "25/12/1989";
$ex = explode("/", $birthDay);
$thisYear = date("Y");
$bDay = mktime("00", "00", "00", $ex['1'], $ex['0'], $thisYear);
$age = $thisYear-$ex['2'];
if(time() < $bDay)
{
$age--;
}
echo $age;
The first two lines define the birthday (DD/MM/YYYY) and then explodes the birthday where it finds a slash (/). This allows to access each part of the birth date individually.$ex = explode("/", $birthDay);
$thisYear = date("Y");
$bDay = mktime("00", "00", "00", $ex['1'], $ex['0'], $thisYear);
$age = $thisYear-$ex['2'];
if(time() < $bDay)
{
$age--;
}
echo $age;
In the next three lines we first get the current year using the date() function. Once we have that stored we create a unix timestamp for the birthday THIS year. Finally for this block we substract the birth date year from the current year.
The variable $age will now contain the persons age IF they have already had their birthday this year, because of this we need to do one final check to see if they have had their birthday this year.
We use an IF statement to check the current timestamp (using PHPs time() function) against the timestamp created for their birthday this year.
If the current timestamp is less then the timestamp for the birthday this year, then they haven't had the birthday this year. As a result, decrement the $age variable to reflect this.
We can then echo the $age variable knowing the persons age (or perform other actions if neccessary).
Hope that helps somebody.


