A few days ago I was looking for a php function that showed the date/time format like on the site Digg (ex: 15 min 20 sec ago). I found two different php functions on the internet that almost achieved what I was looking for, at these links:

woork.blogspot.com/2007/10/time-and-date-difference-using-php.html
drupal.org/node/61565

But it wasn't exactly what I wanted so I wrote my own php function for it, check it out below.

function timeAgo($timestamp, $granularity=2, $format='Y-m-d H:i:s'){

        $difference = time() - $timestamp;
       
        if($difference < 0) return '0 seconds ago';             // if difference is lower than zero check server offset
        elseif($difference < 864000){                                   // if difference is over 10 days show normal time form
       
                $periods = array('week' => 604800,'day' => 86400,'hr' => 3600,'min' => 60,'sec' => 1);
                $output = '';
                foreach($periods as $key => $value){
               
                        if($difference >= $value){
                       
                                $time = round($difference / $value);
                                $difference %= $value;
                               
                                $output .= ($output ? ' ' : '').$time.' ';
                                $output .= (($time > 1 && $key == 'day') ? $key.'s' : $key);
                               
                                $granularity--;
                        }
                        if($granularity == 0) break;
                }
                return ($output ? $output : '0 seconds').' ago';
        }
        else return date($format, $timestamp);
}


The first argument in the function is just a normal time stamp of your item which you probably fetch from your MySQL, the second "granularity" is how far you go in the precision of your date. For example:

-granularity = 4 => 1day, 5hr, 23min, 12sec ago
-granularity = 2 => 1day, 5hr ago

The third parameter is the date format to be used when the time difference is over 10 days (notice the 864000 in the function, that's 10*24*60*60), so when the difference is 10 days or over the function shows the date in the format you choose. Of course you can change the 10 days in to whatever you like.

You can download the php file here: PHP Time Ago Function

How to use it?

Just include the timeAgo.php file in your PHP file that will use the function.

<?php include('timeAgo.php') ?>

...and call the function when needed:

timeAgo($dateRef);

...where $dateRef is, for example, a value from a SQL query.