23 May, 2010

Calculate age in year, month and days from birthdate using php

Following code can be used to get the age using php. Simple php date functions is be used to calculate age
from birth date using php

//find the age using php
//get the birth date
$inpDate = "1983-12-30";
//seperate the birth date day, month and year
list($inpYear, $inpMonth, $inpDay) = explode("-", $inpDate);
//get number of days in a month using following php function
$numOfDays = cal_days_in_month(CAL_GREGORIAN, $inpMonth, $inpYear);
//check if the day inputted is greater then number of days in month and set appropriately
if($inpDay > $numOfDays) {
$inpDay = $numOfDays;
}
//set month to 12 if greater then 12
if($inpMonth > 12) {
$inpMonth = 12;
}
//get the difference in year
$diffYear = date("Y") - $inpYear;
//get the difference in month
$diffMonth = date("m") - $inpMonth;
//get the day difference
$diffDay = date("d") - $inpDay;
//check if month is less than 0
if($diffMonth < 0) {
$diffYear -= 1;
$diffMonth += 12;
}
//check if the day is less than 0
if($diffDay < 0) {
$diffMonth -= 1;
$diffDay += $numOfDays;
}
echo "
";
echo $diffYear. "years";
echo "
";
echo $diffMonth." months";
echo "
";
echo $diffDay." days";
?>

No comments: