Time Difference Function

If you find this code useful and would like to encourage me to post more goodies here, you could buy me something from my wish lists at Amazon.com or at MusicDirect.com

This is a function I came up with recently for getting the difference between two times in terms of years, months, weeks, days, hours, minutes, and seconds. (For example, the difference between now and the same time ten days ago would be 0 years, 0 months, 1 week, 3days, 0 hours, 0 minutes, and 0 seconds.)

<?php
/**
* array timeDiff(int $t1, int $t2)
* $t1 and $t2 must be UNIX timestamp integers, order does not matter
* returns array broken down into years/months/weeks/etc.
*/
function timeDiff($t1, $t2)
{
   if($t1 > $t2)
   {
      $time1 = $t2;
      $time2 = $t1;
   }
   else
   {
      $time1 = $t1;
      $time2 = $t2;
   }
   $diff = array(
      'years' => 0,
      'months' => 0,
      'weeks' => 0,
      'days' => 0,
      'hours' => 0,
      'minutes' => 0,
      'seconds' =>0
   );
   
   foreach(array('years','months','weeks','days','hours','minutes','seconds')
         as $unit)
   {
      while(TRUE)
      {
         $next = strtotime("+1 $unit", $time1);
         if($next < $time2)
         {
            $time1 = $next;
            $diff[$unit]++;
         }
         else
         {
            break;
         }
      }
   }
   return($diff);
}
?>

Here's one example of how to use it:

<?php
$start = strtotime('2007-01-15 07:35:55');
$end = strtotime('2009-11-09 13:01:00');
$diff = timeDiff($start, $end);
$output = "The difference is:";
foreach($diff as $unit => $value)
{
   echo " $value $unit,";
}
$output = trim($output, ',');
echo $output;
?>

This would output: "The difference is: 2 years, 9 months, 3 weeks, 4 days, 5 hours, 25 minutes, 4 seconds"