July 8, 2013

PHP Function – Time Difference or Time Ago

PHP Function – Time Difference or Time Ago

function _ago($time_to, $time_from = 0) {
if($time_from==0) time();
$rtc = 60*60*24; //ROUND THE CLOCK
$total_weeks = 52.177457; //ESTIMATE NO. OF WEEKS
$years = (int)((($time_from - $time_to)/(7*$rtc))/$total_weeks);
$rem = (int)(($time_from-$time_to)-($years * $total_weeks * 7 * $rtc));
$weeks = (int)(($rem)/(7*$rtc));
$days = (int)(($rem)/$rtc) - $weeks*7;
$hours = (int)(($rem)/3600) - $days*24 - $weeks*7*24;
$mins = (int)(($rem)/60) - $hours*60 - $days*24*60 - $weeks*7*24*60;
$output = '';
if($years==1) $output .= "$years year, ";
if($years>1) $output .= "$years years, ";
if($weeks==1) $output .= "$weeks week, ";
if($weeks>1) $output .= "$weeks weeks, ";
if($days==1) $output .= "$days day,";
if($days>1) $output .= "$days days,";
if($hours == 1) $output .= " $hours hour and";
if($hours>1) $output .= " $hours hours and";
if($mins == 1) $output .= " 1 minute";
else $output .= " $mins minutes";
return $output;
}

Last updated: March 19, 2014