views:

326

answers:

3

Possible Duplicate:
Calculate years from date

Hi,

I have a table with a field representing the birthday. How do I find the age of the person from that date?

This is what I have.

$qPersoonsgegevens = "SELECT * FROM alg_persoonsgegevens WHERE 
alg_persoonsgegevens_leerling_ID = $leerling_id";

$rPersoonsgegevens = mysql_query($qPersoonsgegevens);
$aPersoonsgegevens = mysql_fetch_assoc( $rPersoonsgegevens );

$timeBirthdate = mktime($aPersoonsgegevens['alg_persoonsgegevens_geboortedatum']);

Unfortunately, I don't know how to proceed from that point to get the age.

Any help is much appreciated.
Matthy

+5  A: 

This has been asked before. Try this:

function getAge($then) {
    $then = date('Ymd', strtotime($then));
    $diff = date('Ymd') - $then;
    return substr($diff, 0, -4);
}

Call it like so:

$age = getAge($aPersoonsgegevens['alg_persoonsgegevens_geboortedatum']);
Paolo Bergantino
Almost everything can be solved with strtotime(its like magic)
Chacha102
+3  A: 

Birthdays and Ages are Culturally Dependent

It may be useful to remember that some cultures start counting your age from conception or start counting at 1 year old at the time of birth. In particular, you will need to be careful of the Korean market when doing age calculation.

I doubt that the author of the question needs this information, but I just wanted to shout it out since it might be useful to a programmer somewhere and at sometime.

Elijah
A: 

I wrote an app that displays the age for babies (up to 24 months) in months or days (for babies under 1 month old):

public function getAge ()
{
  if ($this->getBirthDate() === null) {
return null;
  }

  if (! $this->getAdmitTime() == null ) {
$relative_to = $this->getAdmitTime(null);  # null format returns Unix ts
  }
  else {
$relative_to = time(); # Unix ts
  }

  $age_in_seconds = $relative_to - $this->getBirthDate(null);
  $age_in_years = intval($age_in_seconds / (60*60*24*365.25));

  if ($age_in_years >= 2) {
return $age_in_years;
  }
  else {
$age_in_months = intval($age_in_seconds / (60*60*24*30));
if ($age_in_months >= 1) {
  return "$age_in_months month". ($age_in_months == 1 ? '' : 's');
}
else {
  $age_in_days = intval($age_in_seconds / (60*60*24));
  return "$age_in_days day" . ($age_in_days == 1 ? '' : 's');
}
  }

}

So you might have these human-readable age values:

  • 21
  • 3
  • 17 months
  • 3 days
Nathan