Skip to content

Instantly share code, notes, and snippets.

@jamalnasir
Last active April 29, 2018 07:17
Show Gist options
  • Save jamalnasir/e15e15b9c2d90839fc7d794224b9df44 to your computer and use it in GitHub Desktop.
Save jamalnasir/e15e15b9c2d90839fc7d794224b9df44 to your computer and use it in GitHub Desktop.
Ago Function in PHP
<?php
function ago($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';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment