PHP Function: Posted Time Ago – Facebook Style

So I won’t claim credit to this but I was browsing DevNetwork and I found a function that is both useful, succinct and awesome all rolled up into one. Using a php lookup table you can calculate the time since something was posted in PHP ie “so and so posted x time ago” facebook style.

function time_passed($timestamp)
{
     $diff = time() - (int)$timestamp;

     if ($diff == 0) 
          return 'just now';

     $intervals = array
     (
         1                   => array('year',    31556926),
         $diff < 31556926    => array('month',   2628000),
         $diff < 2629744     => array('week',    604800),
         $diff < 604800      => array('day',     86400),
         $diff < 86400       => array('hour',    3600),
         $diff < 3600        => array('minute',  60),
         $diff < 60          => array('second',  1)
     );

      $value = floor($diff/$intervals[1][1]);
      return $value.' '.$intervals[1][0].($value > 1 ? 's' : '').' ago';
}

You may also like...

Leave a Reply