tags:

views:

1242

answers:

3

Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?

+13  A: 

Here is the php code for the same:

function time_since($since) {
    $chunks = array(
        array(60 * 60 * 24 * 365 , 'year'),
        array(60 * 60 * 24 * 30 , 'month'),
        array(60 * 60 * 24 * 7, 'week'),
        array(60 * 60 * 24 , 'day'),
        array(60 * 60 , 'hour'),
        array(60 , 'minute'),
        array(1 , 'second')
    );

    for ($i = 0, $j = count($chunks); $i < $j; $i++) {
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];
        if (($count = floor($since / $seconds)) != 0) {
            break;
        }
    }

    $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
    return $print;
}

The function takes the number of seconds as input and outputs text such as:

  • 10 seconds
  • 1 minute

etc

Niyaz
Nice function :)
AntonioCS
Oh and don't forget to change those multiplications with the real values, so that it won't be calculated every time it runs :)
AntonioCS
Since I was curious, replacing the multiplication sequences with the evaluated products was ~1.2% faster.
Mike B
+5  A: 

This has been covered (though with more of a C# focus) in this thread.

Ian Nelson
+2  A: 

This question was previously asked, the example code in answers should be pretty easy to convert to PHP.

Wedge