An useful php function to calculate a time difference between two dates given in sql format. If the newer date is not passed as second argument it would calculate the different between the old date and current time. So it would work as a “ago in words” kind of function as well.
Example use:
humantimediff("2015-02-26 09:35:11", "2015-03-07 11:03:25");
Would say, 1 week 2 days 1 hour 28 minutes 14 seconds
[php]/**
* humantime – convert a time string to human readable time difference
* @param $oldtime – strtotime() of date/time string
* @param $newtime – strtotime() of date/time string
*/
function humantime ($oldtime, $newtime = null, $returnarray = false) {
if(!$newtime) $newtime = time();
$time = $newtime – $oldtime; // to get the time since that moment
$tokens = array (
31536000 => ‘year’,
2592000 => ‘month’,
604800 => ‘week’,
86400 => ‘day’,
3600 => ‘hour’,
60 => ‘minute’,
1 => ‘second’
);
$htarray = array();
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
$htarray[$text] = $numberOfUnits.’ ‘.$text.(($numberOfUnits>1)?’s’:”);
$time = $time – ( $unit * $numberOfUnits );
}
if($returnarray) return $htarray;
return implode(‘ ‘, $htarray);
}
function humantimediff($old_dt, $new_dt) {
$new_dt = $new_dt ? strtotime($new_dt) : null;
return humantime(strtotime($old_dt), $new_dt);
}[/php]