Skip to content

Instantly share code, notes, and snippets.

@azjezz
Created October 23, 2018 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azjezz/6f6c67731c5d9e6cc948a6dd400e3eec to your computer and use it in GitHub Desktop.
Save azjezz/6f6c67731c5d9e6cc948a6dd400e3eec to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
// based on SO answer by Galvic
// https://stackoverflow.com/a/18602474/7427482
function timeago(DateTime $ago, bool $full = false): string {
$now = new DateTime();
$diff = $now->diff($ago);
$values = [
'year' => $diff->y,
'month' => $diff->m,
'week' => $w = floor($diff->d / 7),
'day' => $diff->d - ($w * 7),
'hour' => $diff->h,
'minute' => $diff->i,
'second' => $diff->s,
];
foreach ($values as $key => $value) {
if ($value > 0) {
$values[$key] = $value . ' ' . $key . ($value > 1 ? 's' : '');
} else {
unset($values[$key]);
}
}
if (!$full) {
$values = array_slice($values, 0, 1);
}
return count($values) > 0 ? implode(', ', $values) . ' ago' : 'just now';
}
echo timeago(new DateTime('@1578')) . PHP_EOL; // 48 years ago
echo timeago(new DateTime('@1578'), true) . PHP_EOL; // 48 years, 9 months, 3 weeks, 1 day, 16 hours, 30 minutes ago
echo timeago(new DateTime()) . PHP_EOL; // just now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment