Jump to content

Age from Year, Month, Day


Seraskier

Recommended Posts

Subtract the birth year from the current year.  Then if the birth day hasn't happend this year, subtract 1.
[code]<?php
$currentYear = date("Y");
$currentMonth = date("n");
$currentDay = date("j");

$birthday = 27;
$birthmonth = 11;
$birthyear = 1980;

$age = $currentYear - $birthyear;
$a = mktime(1,0,0,$currentDay, $currentMonth, $currentYear);
$b = mktime(1,0,0,$birthday,$birthmonth,$currentYear);
if ($a < $b){
  $age--;
}
echo "<br />Current Month:  " . $currentMonth;
echo "<br />Current Day:  " . $currentDay;
echo "<br />Current Year:  " . $currentYear;
echo "<br/><br />Birth Month:  " . $birthmonth;
echo "<br />Birth Day:  " . $birthday;
echo "<br />Birth Year:  " . $birthyear;
echo "<br /><br />Age:  " . $age;
?>
[/code]
P.S. the 1, 0, 0 in the mktime function calls represent HOUR, MINUTE, SECOND.  I'm just making sure we're looking at the same time of day on both the birthday and current day.  That was also a little lengthy--I did it that way to make it easy to follow.

It could be boiled down to this:
[code]
<?php
$birthday = 27;
$birthmonth = 11;
$birthyear = 1980;

$age = date("Y") - $birthyear;
if (mktime(1,0,0,date("j"), date("n"), date("Y")) < mktime(1,0,0,$birthday,$birthmonth,date("Y"))){
  $age--;
}
echo "<br /><br />Age:  " . $age;
?>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.