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;
}
Code language: PHP (php)
Mazen
Genius… Will try to apply it on an iPhone app… thanks
Sergio
HI, GOOD CODE this is using foreach
if( !is_numeric( $timestamp ) ){
$timestamp = strtotime( $timestamp );
if( !is_numeric( $timestamp ) ){
return “";
}
}
$difference = time() – $timestamp;
$lengths = array(“segundo"=>60,"minuto"=>60,"hora"=>24,"día"=>7,"semana"=>4.35,"mes"=>12,"año"=>10,"decada"=>100,"siglo"=>1000);
if ($difference > 0) {
$ending = “ago";
}else {
$difference = -$difference;
$ending = “from";
}
$salida=array();
foreach($lengths as $periodo=>$limite){
$salida[$periodo]=$difference;
$difference /= $limite;
$difference = round($difference);
}
foreach($salida as $periodo=>$diferencia){
if($diferencia>1){$periodo=$periodo.'s';}
if($diferencia>=1){
$genera=$ending.' '.$diferencia.' '.$periodo;
}
}
return $genera;
}
Rick
Thanks for the tip !
kevin
In order to add an “s” to the end of the current period, it looks as though you may want to move the
if($difference != 1)
logic to just AFTER the
loop. Otherwise it seems to only add plural endings to all periods prior to the one that really matters.