Last active
December 20, 2015 00:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is wonderful