PHP: How To Get A Time Difference in Human Readable Format

A simple function to return the time since a given timestamp in the past.

function time_since($timestamp) {

  // Init
  $hash = array();
  $now = time();

  // Breakdown the time diff
  $diff = $now - $timestamp;
  $hash['day'] = floor($diff / 86400);
  $diff = $diff % 86400;
  $hash['hour'] = floor($diff / 3600);
  $diff = $diff % 3600;
  $hash['minute'] = floor($diff / 60);
  $hash['second'] = $diff % 60;

  // Build the return string
  $string = '';
  foreach ($hash as $unit => $amount) {
    if ($amount > 0) {
      if ($amount > 1) $unit .= 's';
      $string .= "$amount $unit ";
    }
  }
  $string .= 'ago';

  return $string;
}

Example:

$stat = stat($filename);
$mtime = $stat[9];
$string = time_since($mtime)
echo $string;
// prints "12 days 11 hours 10 minutes 9 seconds ago"

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

One Response to PHP: How To Get A Time Difference in Human Readable Format

  1. Tifka says:

    I like +34

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>