Friday, July 29, 2011

Calculate time-diff and calculate age from birth date

On my searches I've found many many different, complicated functions for time difference and many different functions calculate age, But for such a simple task I thought there should be a simpler solution.
so here are a few good simple ways to calculate time differences and age

good and simple function that because of the versatility of strtotime function can support many different date formats:

function dateDiff($from, $to = "now")
{
return round((strtotime($to) - strtotime($from))/60/60/24);
}

and if age calculation is what you desire,
a simple function to calculate age by birth date

/**
* Calc age from MySQL date format
* @param string $date YY-mm-dd (MySQL Date Format)
*/
function calcAge($date)
{
//Break the date into an array
list($Y,$m,$d) = explode("-",$date);
//Calculate Year Diff
$age = date("Y")-$Y;
//Subtract a year if exact birth date hasn't passed yet
if(date("md") < $m.$d) $age--;
//And finally return the age
return $age;
}

No comments:

Post a Comment