How to calculate relative time like facebook
I’ve found this cool snippet witch returns the relative time from a given date.
Just like facebook does posted 20 minutes ago.
You can translate it from English to any language. Just make sure you edit the $periods array.
function RelativeTime( $timestamp ){
if( !is_numeric( $timestamp ) ){
$timestamp = strtotime( $timestamp );
if( !is_numeric( $timestamp ) ){
return "";
}
}
$difference = time() - $timestamp;
// Customize in your own language.
$periods = array( "sec", "min", "hour", "day", "week", "month", "years", "decade" );
$lengths = array( "60","60","24","7","4.35","12","10");
if ($difference > 0) { // this was in the past
$ending = "ago";
}else { // this was in the future
$difference = -$difference;
$ending = "to go";
}
for( $j=0; $difference>=$lengths[$j] and $j < 7; $j++ )
$difference /= $lengths[$j];
$difference = round($difference);
if( $difference != 1 ){
// Also change this if needed for an other language
$periods[$j].= "s";
}
$text = "$difference $periods[$j] $ending";
return $text;
}
if( !is_numeric( $timestamp ) ){
$timestamp = strtotime( $timestamp );
if( !is_numeric( $timestamp ) ){
return "";
}
}
$difference = time() - $timestamp;
// Customize in your own language.
$periods = array( "sec", "min", "hour", "day", "week", "month", "years", "decade" );
$lengths = array( "60","60","24","7","4.35","12","10");
if ($difference > 0) { // this was in the past
$ending = "ago";
}else { // this was in the future
$difference = -$difference;
$ending = "to go";
}
for( $j=0; $difference>=$lengths[$j] and $j < 7; $j++ )
$difference /= $lengths[$j];
$difference = round($difference);
if( $difference != 1 ){
// Also change this if needed for an other language
$periods[$j].= "s";
}
$text = "$difference $periods[$j] $ending";
return $text;
}
Related PostsIf you liked How to calculate relative time like facebook; the posts below might interest you too:
|




October 26, 2011
17:07
Genius… Will try to apply it on an iPhone app… thanks