Relative Time Ago Formatter
PHP Code Editor
Execution Result
Ready to execute
Click the "Run Script" button to see the output here
Description
Interfaces constantly show timestamps as 5 minutes ago or 2 days ago instead of raw dates, because relative time is easier to read at a glance for recent events. The logic is simple but full of small mistakes people make, like off-by-one pluralization or dividing by the wrong number of seconds in a month, so it is worth having a clean reference version.
This function diffs the given time against now in whole seconds, then walks a table of unit sizes from year down to second and returns the first unit that fits at least once, computing the count with integer division and pluralizing only when the count is more than one. Future timestamps and the just-now case under one second are handled explicitly rather than producing a nonsensical result.
function timeAgo(DateTimeInterface $then, ?DateTimeInterface $now = null): string {
$now ??= new DateTimeImmutable('now', $then->getTimezone());
$diff = $now->getTimestamp() - $then->getTimestamp();
if ($diff < 0) {
return 'in the future';
}
if ($diff < 1) {
return 'just now';
}
$units = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second',
];
foreach ($units as $seconds => $name) {
if ($diff >= $seconds) {
$count = intdiv($diff, $seconds);
return $count . ' ' . $name . ($count > 1 ? 's' : '') . ' ago';
}
}
return 'just now';
}
$past = new DateTimeImmutable('-3 hours -20 minutes');
echo timeAgo($past) . "\n"; // 3 hours ago
echo timeAgo(new DateTimeImmutable('-2 days')) . "\n"; // 2 days ago
Comments
No comments yet
Be the first to share your thoughts!