Calculate users age with PHP

Recently I needed some code to calculate a users age based on their birthday. There are many different functions that are already created out there that I could have used, but instead I wrote this piece of code. It uses PHP 5 DateTime class to return an array of information pertaining to how old a person is. By default if you leave the second parameter off it will calculate the difference from the start date to the current day. If you are trying to calculate how old somebody was when they had passed away or how old they were on a certain date you can pass the second parameter. There are several different checks in this code snippet to make sure you are using a valid date for the start and end date.

This function requires dates to be passed in standard: YYYY-MM-DD format
Code:

<?php
if (!function_exists('calculate_age')) {
        /*
        Author: Daniel Kassner
        Website: http://www.danielkassner.com
        */
	// Checked this function against http://www.timeanddate.com/date/duration.html

	function calculate_age($startdate = '0000-00-00', $enddate = '0000-00-00') {
		
		// Check to see if start date is valid

		@list($year, $month, $day) = explode('-', $startdate);
		if (@!checkdate($month,$day,$year)) {
			return false;
		}
		
		// Create a new datetime object to do our calculations with
		$s = new DateTime($startdate);
		// We have to have an end date so if it is empty or 0000-00-00 we will make it right now
		if (empty($enddate) OR $enddate == '0000-00-00') {
			$enddate = 'now';
		} else {
			// Check to see if end date is valid

			@list($year, $month, $day) = explode('-', $enddate);
			if (@!checkdate($month,$day,$year)) {
				return false;
			}
		}
		// Create a new datetime object to compare as an end date
		$e = new DateTime($enddate);
		
		if ($s->format('Ymd') > $e->format('Ymd')) {
			// End date cannot be before start date
			return false;
		}
		
		// Calculate our base numbers here
		$years = $e->format('Y')-$s->format('Y');
		$months = $e->format('m')-$s->format('m');
		$days = $e->format('d')-$s->format('d');

		// We cannot have negative days
		// Calculate how many days are in the startdate month
		// subtract the startdate day and add 1
		// Then add back in the day of the enddate
		// Subtract 1 month
		if ($days < 0) {
			$days = $s->format('t')-$s->format('d')+1;
			$days += $e->format('d');
			$months--;
		}
		
		// We cannot have negative months
		// Subtract 1 year and add back 12 months to make months positive
		if ($months < 0) {
			$years--;
			$months += 12;
		}

		return array('years'=>$years,'months'=>$months, 'days'=>$days);
	}
}
?>

Usage:

<?php
// Current date is 2010-01-19
$birthday = '1987-09-23';
$age = calculate_age($birthday);
var_dump($age);
echo '<hr />';
$startdate = '1985-09-06';
$enddate = '1987-09-23';
$difference = calculate_age($startdate, $enddate);
var_dump($difference);
?>

Output:

array(3) { ["years"]=> int(22) ["months"]=> int(3) ["days"]=> int(27) }
——————————————————————————————————–
array(3) { ["years"]=> int(2) ["months"]=> int(0) ["days"]=> int(17) }

  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • BlinkList
  • FriendFeed
  • LinkedIn
  • MySpace
  • Slashdot
  • StumbleUpon
  • Twitter
  • Yahoo! Bookmarks
  • Add to favorites
  • email

5 Responses to “Calculate users age with PHP”

  1. Piotr Says:

    Thanks for this great script!

    It is exactly what I needed to calculate the exact difference between 2 dates.
    You saved me a lot of time!


  2. León Says:

    Daniel,

    Thanks for posting your function. After using it with several different birth dates I found that the days were not being calculated correctly. The problem was the correction of negatives days, which substracts the start date day from the total number of days in the start date month, when they should be subsctracted from the last completed month (end date month – 1).

    This is what I did:


    // We cannot have negative days
    // Calculate how many days are in the startdate month // Not the startdate month, but the last completed month (end date month - 1)
    // subtract the startdate day and add 1 // Not necessary to add 1
    // Then add back in the day of the enddate
    // Subtract 1 month
    if ($days format('Y')."-".($e->format('m')-1)."-".$s->format('d');
    $fakeStartDate = new DateTime($fakeStartDateString);
    $days = $fakeStartDate->format('t')-$s->format('d');
    //$days = $s->format('t')-$s->format('d');//+1;
    $days += $e->format('d');
    $months--;
    }

    It now works perfectly fine.

    I hope someone finds this useful.

    Greetings,

    León Glz.
    Mexico


  3. León Says:

    Something messed up my last post. The first two lines of code should be:

    if($days format(‘Y’).”-”.($e->format(‘m’)-1).”-”.$s->format(‘d’);


  4. León Says:

    Again.

    if ($days format(‘Y’).”-”.($e->format(‘m’)-1).”-”.$s->format(‘d’);


  5. León Says:

    I’m sorry. I think the “less than” symbol is messing up the post. I’ll try one last time and if it doesn’t work I’ll just give up.

    The first two lines of the code I posted originally should be:

    if($days < 0) {
    $fakeStartDateString = $s->format(‘Y’).”-”.($e->format(‘m’)-1).”-”.$s->format(‘d’);

    Sorry for flooding your post.


Switch to our mobile site