How easy is it to determine the age from the birthday? (PHP)

Possible duplicate:
Calculate years from date

Hello,

I have a table with a birthday field. How to find out the age of a person from this 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 start from this point in order to get the age.

Any help is greatly appreciated. Matthy

0


source to share


3 answers


This has been asked before. Try the following:

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

      



Call it like this:

$age = getAge($aPersoonsgegevens['alg_persoonsgegevens_geboortedatum']);

      

+7


source


Birthdays and eras are culturally dependent

It may be helpful to remember that some cultures start counting your age at conception or counting at 1 year of age at birth. In particular, you will need to be careful with the Korean market when calculating your age.



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 the programmer somewhere and someday.

+3


source


I wrote an app that shows ages 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 can have these human-readable age values:

  • 21
  • 3
  • 17 months
  • 3 days
+1


source







All Articles