Quick Tip: Easily Readable Relative Time Difference in PHP

Posted May 25, 2009 @ 5:03pm by Phil

I created this function recently for the Twitter Updates section to the right. It returns an easily readable difference in the current time and the provided time stamp such as "4 hours ago" or "in 4 hours" if it's in the future.

<?php
  function date_diff ($stamp)
  {
    $time = time();
    $diff = abs($time - $stamp);
    $value = 0;
    $unit = "";
    
    // Seconds
    if ($diff < 60) { $value = $diff; $unit = "second"; }
    // Minutes
    else if ($diff < 3600) { $value = floor($diff / 60); $unit = "minute"; }
    // Hours
    else if ($diff < 86400) { $value = floor($diff / 3600); $unit = "hour"; }
    // Days
    else { $value = floor($diff / 86400); $unit = "day"; }
    
    if ($value > 1) { $unit .= "s"; }
    
    return ($stamp < $time) ? "$value $unit ago" : "In $value $unit";
  }
?>

Download Source: date_diff.php

Tags: PHP/MySQL, Quick Tip