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; }

About Ricard Torres

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

5 comments
  • Genius… Will try to apply it on an iPhone app… thanks

  • 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;
    }

  • 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

    for

    loop. Otherwise it seems to only add plural endings to all periods prior to the one that really matters.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*