Skip to content

Instantly share code, notes, and snippets.

@jkoop
Created January 21, 2022 21:47
Show Gist options
  • Save jkoop/3f76bf1e56e384fa5755c47e64719fb9 to your computer and use it in GitHub Desktop.
Save jkoop/3f76bf1e56e384fa5755c47e64719fb9 to your computer and use it in GitHub Desktop.
<?php
function relativeTime(int|float|string $time): string {
static $minute = 60;
static $hour = 60 * 60;
static $day = 24 * 60 * 60;
static $month = 30 * 24 * 60 * 60;
static $year = 365 * 24 * 60 * 60;
if (!is_numeric($time)) {
$time = strtotime($time);
if ($time === false) {
return '[invalid time]';
}
}
$delta = time() - $time;
$direction = $delta / abs($delta);
$delta = abs($delta);
if ($delta < $minute) {
return $direction > 0 ? 'just now' : 'soon';
} else if ($delta < $hour) {
$count = round($delta / $minute);
$unit = 'minute';
} else if ($delta < $day) {
$count = round($delta / $hour);
$unit = 'hour';
} else if ($delta < $month) {
$count = round($delta / $day);
$unit = 'day';
} else if ($delta < $year) {
$count = round($delta / $month);
$unit = 'month';
} else {
$count = round($delta / $year);
$unit = 'year';
}
return $count . ' ' . $unit . ($count == 1 ? '' : 's') . ($direction > 0 ? ' ago' : ' from now');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment