-
Notifications
You must be signed in to change notification settings - Fork 7.6k
Fuzzy time
Gowri sankar.R edited this page Sep 24, 2013
·
7 revisions
Fuzzy times - not a reference to everyone's favourite Muppet, last Friday evening, or 1970's porn - but instead the ability to take a timestamp and return a string like 'less than a minute ago' or '3 days ago'.
Often seen on social sites to provide a more friendly feel than, say, '3 hours, 15 minutes and 48 seconds ago' would.
This page should consolidate the various ways, often hidden deep in the forums, of accomplishing this fairly common, and straightforward, task.
Approach The First
ebot posted a relative timeline function you can drop straight into your helper.
if ( ! function_exists('when'))
{
function when($dt,$precision=2)
{
$times=array( 365*24*60*60 => "year",
30*24*60*60 => "month",
7*24*60*60 => "week",
24*60*60 => "day",
60*60 => "hour",
60 => "minute",
1 => "second");
$passed=time()-$dt;
if($passed<5)
{
$output='less than 5 seconds ago';
}
elseif($passed > 172800)
{
$output=date("jS F,Y",$dt);
}
else
{
$output=array();
$exit=0;
foreach($times as $period=>$name)
{
if($exit>=$precision OR ($exit>0 && $period<60)) break;
$result = floor($passed/$period);
if($result>0)
{
$output[]=$result.' '.$name.($result==1?'':'s');
$passed-=$result*$period;
$exit++;
}
else
if($exit>0)
$exit++;
}
$output=implode(', ',$output).' ago';
}
return $output;
}
}