Feb 10 2010

PHP how to calculate age from date of birth

Category: PhpGiulio Pons @ 10:59 am

This is a very simple script that starts from a string date in format yyyy-mm-dd and return the age.
To do this it splits the date, calculate years with difference from current year and the fix the value based on difference between months and days from current date:

// input $date string format: YYYY-MM-DD
function age($date){
	list($year,$month,$day) = explode("-",$date);
	$year_diff  = date("Y") - $year;
	$month_diff = date("m") - $month;
	$day_diff   = date("d") - $day;
	if ($day_diff < 0 || $month_diff < 0) $year_diff--;
	return $year_diff;
}
  • Share/Bookmark

Tags: , ,


Nov 11 2009

PHP Day add function

Category: PhpGiulio Pons @ 3:06 pm

How to add 2 days to a date in PHP?
There are many ways to add days to a string date. The best function is the following one:

function dayadd($days,$date=null , $format="d/m/Y"){
	return date($format,strtotime($days." days",strtotime( $date ? $date : date($format) )));
}

This function let you decide the date to which add the days, the output format and days to add. To use the function look these examples:

echo dayadd(2);  // 2 days after today
echo dayadd(-2,null,"Y-m-d");  // 2 days before today with given format
echo dayadd(3,"12/31/2009");  // 3 days after given date
echo dayadd(3,"12/31/2009","d-m-Y");  // 3 days after given date with given format
  • Share/Bookmark

Tags: , , ,