Skip to content

Instantly share code, notes, and snippets.

@kmaida
Last active December 20, 2015 00:59
Show Gist options
  • Save kmaida/6045690 to your computer and use it in GitHub Desktop.
Save kmaida/6045690 to your computer and use it in GitHub Desktop.
Calculating time between now and timestamp in the fashion of GitHub commit listings.
function timeAgo($dateStr) {
$timestamp = strtotime($dateStr);
$timeUnits = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute')
);
$today = time(); // Current unix time
$since = $today - $timestamp;
for ($i = 0, $j = count($timeUnits); $i < $j; $i++) {
$seconds = $timeUnits[$i][0];
$units = $timeUnits[$i][1];
if (($count = floor($since / $seconds)) != 0) {
break;
}
}
$single = ($units == 'hour') ? 'an ' : 'a ';
$print = ($count == 1) ? $single . $units : "$count {$units}s";
return $print . ' ago';
}
@TheRealKira
Copy link

This is wonderful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment