tags:

views:

136

answers:

4

I've got a small custom made blog type thing and want to display the date posted next to comments.

I'd like to do it in the format of:

posted 23 secs ago
posted 43mins ago
posted 1hr ago
posted 1day ago
posted 2 weeks ago
... probably won't get much longer than that because articles older than a month aren't shown.

I can stored the actual date in datetime or timestamp format in MySQL...

Anyone know of a function that's existing for PHP which I could use to do this? I haven't really found anything that suits yet.

+1  A: 

As far as I know, there is no function built in to PHP to accomplish this, but there do seem to be functions already written for this purpose.

The one here seems to be able to do what you need it to. (you might need to tweak it a bit)

mtwstudios
A: 

You can use the following function and call it as format_interval(time() - $saved_timestamp), where $saved_timestamp is the timestamp of the "event" you are interested in.

function format_interval($timestamp, $granularity = 2) {
  $units = array('1 year|@count years' => 31536000, '1 week|@count weeks' => 604800, '1 day|@count days' => 86400, '1 hour|@count hours' => 3600, '1 min|@count min' => 60, '1 sec|@count sec' => 1);
  $output = '';
  foreach ($units as $key => $value) {
    $key = explode('|', $key);
    if ($timestamp >= $value) {
      $floor = floor($timestamp / $value);
      $output .= ($output ? ' ' : '') . ($floor == 1 ? $key[0] : str_replace('@count', $floor, $key[1]));
      $timestamp %= $value;
      $granularity--;
    }

    if ($granularity == 0) {
      break;
    }
  }

  return $output ? $output : '0 sec';
}
kiamlaluno