Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm looking for a function that calculates years from a date in format: 0000-00-00. Found this function, but it wont work.

// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
  // Explode the date into meaningful variables
  list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
  // Find the differences
  $YearDiff = date("Y") - $BirthYear;
  $MonthDiff = date("m") - $BirthMonth;
  $DayDiff = date("d") - $BirthDay;
  // If the birthday has not occured this year
  if ($DayDiff < 0 || $MonthDiff < 0)
  $YearDiff--;
 }

echo getAge('1990-04-04');

outputs nothing :/
i have error reporting on but i dont get any errors

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
436 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your code doesn't work because the function is not returning anything to print.

As far as algorithms go, how about this:

function getAge($then) {
    $then_ts = strtotime($then);
    $then_year = date('Y', $then_ts);
    $age = date('Y') - $then_year;
    if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
    return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet

This is the same algorithm (just in PHP) as the accepted answer in this question.

A shorter way of doing it:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...