I found this really nice PHP script that converts any datetime into a relative string, for example:
'2013-05-01 00:22:35' -> '3 months ago'
It's really cool, but I would like to "trick" the function so that even if the date is, let's say, 20 minutes before, the function returns 1 hour ago
instead of 20 minutes ago
. Thus, I want to enforce a minimum difference of 1 hour, even when the difference is less than that.
For reference, here is the function.
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
I tried a lot of different things, but nothing really worked.
How can I enforce a minimum difference of 1 hour?