Calculating an age on a given date with php

16 Jan 2012 | Posted by: Paul whittington
I needed to calculate an age on a given date recently and it takes more thought than meets the eye. I needed to do this to make sure that on a date booked to do a driving experience the participant was old enough for insurance purposes. It is very easy to work out how many secs, mins and hours old they are however years is more of a problem because of the uneven number of days in each year and month. In the end the solution was fairly simple, but it took a while to get there..!
 
 
 
//To get the number of years old someone born on 28th Feb 1971 is on the 1st Jun 2012 use:
list ($yearsOld) = getAgeOnDate (1971, 2, 28, 2012, 6, 1) ;

function getAgeOnDate ($birthYear, $birthMonth, $birthDay, $thisYear, $thisMonth, $thisDay) {
	$yearDiff = $thisYear - $birthYear;
	$monthDiff = $thisMonth - $birthMonth;
	$dayDiff = $thisDay - $birthDay;							
	if ($dayDiff < 0) {
		$monthDiff--;
                // This is the difficult bit...
                // if the days crosses the end of the month
                // You need...                
                // The number of days from the birth day to the end of the birth month
                // Plus 
                // The number of days to this point in the current month

		$dayDiff = cal_days_in_month (CAL_GREGORIAN, $birthMonth, $birthYear) - (-1 * $dayDiff);
	}						
	if ($monthDiff < 0){
		$yearDiff--;
		$monthDiff = 12 - (-1 * $monthDiff);
	}
	return array($yearDiff, $monthDiff, $dayDiff);
}

 


 

Please rate this article

Click the stars below to give this article a mark out of 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 5 / 10


Post your comments...

We would really appreciate any comments or additions that you have. Include a link in your comment and if we think your comment is appropriate we will publish it. If found this article in any way useful we would really appreciate you bookmarking the page with any of the social bookmarking links provided.



Name:
(optional, shown on site)
Email:
(optional, never shown on site)
Code:
(case sensitive)
captcha
Your feedback: