Skip to main content

Calculate age, given date of birth

This class can calculate a person's age and also display values like the number of days and weeks lived.

<?php
class Age
{
var $age = '';

function calculateAge($iTimestamp)
{
$iDiffYear = date('Y') - date('Y', $iTimestamp);
$iDiffMonth = date('n') - date('n', $iTimestamp);
$iDiffDay = date('j') - date('j', $iTimestamp);

// If birthday has not happen yet for this year, subtract 1.
if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
{
$iDiffYear--;
}

$this->age = $iDiffYear;
}

function getAge()
{
return $this->age;
}

function get_rank($rank)
{
$last = substr( $rank, -1 );
$seclast = substr( $rank, -2, -1 );
if( $last > 3 || $last == 0 ) $ext = 'th';
else if( $last == 3 ) $ext = 'rd';
else if( $last == 2 ) $ext = 'nd';
else $ext = 'st';

if( $last == 1 && $seclast == 1) $ext = 'th';
if( $last == 2 && $seclast == 1) $ext = 'th';
if( $last == 3 && $seclast == 1) $ext = 'th';

return $rank.$ext;
}

}

$dob = '1985-06-18';
$dob2 = explode("-",$dob);

$dob_hour = 18; // 24 hour format
$dob_min = 41;
$dob_sec = 0;

$d = getdate(); // Current date

$year=$d['year'];
$mon=$d['mon'];
$mday=$d['mday'];

$hour = $d['hours'];
$min = $d['minutes'];
$sec = $d['seconds'];

$d1=mktime($dob_hour,$dob_min,$dob_sec,$dob2[1],$dob2[2],$dob2[0]);
$d2=mktime($hour,$min,$sec,$mon,$mday,$year);

$obj = new Age;

$obj->calculateAge(mktime($dob_hour,$dob_min,$dob_sec,6,18,1985));

$age = $obj->getAge();
$rank = $obj->get_rank($age+1);

echo 'Your age: '.$age;
echo '<br>';
echo 'You are running: '.$rank.' year';

echo '<br><br>';
echo '<b>You already lived:</b> <br><br>';

echo "Years: ".floor(($d2-$d1)/31536000) . "<br>";
echo "Months: ".floor(($d2-$d1)/2628000) . "<br>";
echo "Weeks: ".floor(($d2-$d1)/604800) . "<br>";
echo "Days: ".floor(($d2-$d1)/86400) . "<br><br>";

echo "Hours: ".floor(($d2-$d1)/3600) . "<br>";
echo "Minutes: ".floor(($d2-$d1)/60) . "<br>";
echo "Seconds: " .($d2-$d1). "<br><br>";
?>

Comments