Calculating age from unix timestamps in PHP

I couldn’t find a function already created for PHP that calculates someone’s age based on their birthdate and the current date (in unix timestamp format – seconds since 1970). First I tried this:

$age = date("Y",$endtime) - date("Y",$starttime);

But then I realized that this might not be completely accurate, base on the calendar, leap year, etc. So here’s what I ended up with:

function computeAge($starttime,$endtime)
{
	$age = date("Y",$endtime) - date("Y",$starttime);
	//if birthday didn't occur that last year, then decrement
	if(date("z",$endtime) < date("z",$starttime)) $age--;
	return $age;
}

Let me know if you have any improvements!


Posted

in

by

Tags:

Comments

3 responses to “Calculating age from unix timestamps in PHP”

  1. Nightmare Avatar
    Nightmare

    Thanks for this function

  2. Rowan Avatar

    thanks for this, I’ve done the same thing but you managed to logically make the code a lot smaller and faster than my method

  3. Tim Avatar

    Doesn’t work for leap years, because the 1st March, and all days thereafter, are one day later than an ordinary year.


    function getYearsSinceDate($date)
    {
    $now = time();
    $then = strtotime($date);
    // get difference between years
    $years = date("Y", $now) - date("Y", $then);

    // get months of dates
    $mthen = date("n", $then);
    $mnow = date("n", $now);
    // get days of dates
    $dthen = date("j", $then);
    $dnow = date("j", $now);
    // if date not reached yet this year, we need to remove one year.
    if ($mnow < $mthen || ($mnow==$mthen && $dnow<$dthen)) {
    $years--;
    }
    return $years;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *