Skip to content

Instantly share code, notes, and snippets.

@paulredmond
Created December 15, 2010 22:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulredmond/742707 to your computer and use it in GitHub Desktop.
Save paulredmond/742707 to your computer and use it in GitHub Desktop.
Function that returns time ago results from a strtotime-friendly string such as a datetime
<?php
function timeago( $params )
{
$conversions = array(
'millisecond' => 1,
'second' => 1000,
'minute' => 60,
'hour' => 60,
'day' => 24,
'month' => 30,
'year' => 12
);
# Set up params.
$threshold = isset($params['threshold']) ? $params['threshold'] : 0;
$now = strtotime('now');
$time = strtotime($params['time']);
$delta = ($now - $time) * 1000;
if ($delta <= $threshold) {
return "Just now";
}
foreach ($conversions as $key => $val) {
if($delta < $conversions[$key]) {
break;
} else {
$units = $key;
$delta = $delta / $conversions[$key];
}
}
$delta = floor($delta);
if($delta != 1) { $units .= 's'; }
return implode(' ', array($delta, $units, 'ago'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment