Display Time That Passed Since a Date

  1. function TimeSince($original) // $original should be the original date and time in Unix format
  2. {
  3.     // Common time periods as an array of arrays
  4.     $periods = array(
  5.         array(60 * 60 * 24 * 365 , 'year'),
  6.         array(60 * 60 * 24 * 30 , 'month'),
  7.         array(60 * 60 * 24 * 7, 'week'),
  8.         array(60 * 60 * 24 , 'day'),
  9.         array(60 * 60 , 'hour'),
  10.         array(60 , 'minute'),
  11.     );
  12.    
  13.     $today = time();
  14.     $since = $today - $original; // Find the difference of time between now and the past
  15.    
  16.     // Loop around the periods, starting with the biggest
  17.     for ($i = 0, $j = count($periods); $i < $j; $i++)
  18.         {    
  19.         $seconds = $periods[$i][0];
  20.         $name = $periods[$i][1];
  21.        
  22.         // Find the biggest whole period
  23.         if (($count = floor($since / $seconds)) != 0)
  24.                 {
  25.             break;
  26.         }
  27.     }
  28.    
  29.     $output = ($count == 1) ? '1 '.$name : "$count {$name}s";
  30.    
  31.     if ($i + 1 < $j)
  32.         {
  33.         // Retrieving the second relevant period
  34.         $seconds2 = $periods[$i + 1][0];
  35.         $name2 = $periods[$i + 1][1];
  36.        
  37.         // Only show it if it's greater than 0
  38.         if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0)
  39.                 {
  40.             $output .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
  41.         }
  42.     }
  43.     return $output;
  44. }
  45.  
  46. echo TimeSince(1249091056);
     
    Reference: http://www.geekpedia.com/code168_Display-Time-That-Passed-Since-a-Date.html


Written by