jgvk jgvk - 3 years ago 108
PHP Question

Format datetime interval with a minimum difference

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?

Answer Source

After you have figured out the difference, simply check if the largest difference is only minutes or seconds. If so, return the minimum of 1 hour that you require.

// here is your foreach loop

// check if less than 1 hour, if so, return that
$keys = array_keys($string);
if ($keys[0] === 'i' || $keys[0] === 's') {
  return 'less than 1 hour ago';
}

Try it online!
I put the time of posting the question in this example. When you look at it more than 1 hour after that, you'll have to modify the test case to a DateTime that is less than 1 hour ago in UTC time.

Test cases. It is now 2017-06-10 12:45:00 in UTC.

time_elapsed_string("2017-06-10 12:11:19"); // less than 1 hour ago
time_elapsed_string("2017-06-10 11:44:00"); // 1 hour ago
time_elapsed_string("2017-06-10 11:44:00", true); // 1 hour, 1 minute ago
time_elapsed_string("2017-06-09 11:45:00", true); // 1 day, 1 hour ago
time_elapsed_string("2017-06-09 11:45:00"); // 1 day ago
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download