Skip to content

Instantly share code, notes, and snippets.

@delianides
Created February 12, 2011 06:48
Show Gist options
  • Save delianides/823568 to your computer and use it in GitHub Desktop.
Save delianides/823568 to your computer and use it in GitHub Desktop.
Modified version of CSS Tricks time ago function to better support ajax.
<?php
function ago($time)
{
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60", "60", "24", "7", "4.35", "12", "10");
$now = time();
$difference = $now - $time;
$tense = "ago";
if($difference < 10){
return "just now";
} else if (($difference > 10)&&($difference < 60)){
return "less than a minute ago";
} else if ($difference > 432000){//Equivalent to 5 days.
return date('M j', $time);
}
for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if ($difference != 1) {
$periods[$j].= "s";
}
return "$difference $periods[$j] ago ";
}
?>
@delianides
Copy link
Author

Ajax support is improved with checking to see if difference is greater than 10 seconds. Otherwise, when adding something dynamically it would appear as '0 seconds ago'. Now it just states, 'just now' and 'less than a minute ago'. If the difference is greater than 5 days, I have it output the date instead.

@delianides
Copy link
Author

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