Advertisement
alchymyth

human time difference

May 13th, 2012
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.57 KB | None | 0 0
  1. /**
  2.  * this code assumes php >= 5.1.0. if using < 5.1, read
  3.  * php.net/strtotime and change the condition for checking
  4.  * for failure from strtotime()
  5.  *
  6.  * by nate in http://www.php.net/manual/en/ref.datetime.php#80866
  7.  */
  8.  
  9. // $t1, $t2: unix times, or strtotime parseable
  10. // $precision: max number of units to output
  11. // $abbr: if true, use "hr" instead of "hour", etc.
  12. function human_date_diff ($t1, $t2, $precision = 6, $abbr = false) {
  13.     if (preg_match('/\D/', $t1) && ($t1 = strtotime($t1)) === false)
  14.         return false;
  15.  
  16.     if (preg_match('/\D/', $t2) && ($t2 = strtotime($t2)) === false)
  17.         return false;
  18.  
  19.     if ($t1 > $t2)
  20.         list($t1, $t2) = array($t2, $t1);
  21.  
  22.     $diffs = array(
  23.         'year' => 0, 'month' => 0, 'day' => 0,
  24.         'hour' => 0, 'minute' => 0, 'second' => 0,
  25.     );
  26.  
  27.     $abbrs = array(
  28.         'year' => 'yr', 'month' => 'mth', 'day' => 'day',
  29.         'hour' => 'hr', 'minute' => 'min', 'second' => 'sec'
  30.     );
  31.  
  32.     foreach (array_keys($diffs) as $interval) {
  33.         while ($t2 >= ($t3 = strtotime("+1 ${interval}", $t1))) {
  34.             $t1 = $t3;
  35.             ++$diffs[$interval];
  36.         }
  37.     }
  38.  
  39.     $stack = array();
  40.     foreach ($diffs as $interval => $num)
  41.         $stack[] = array($num, ($abbr ? $abbrs[$interval] : $interval) . ($num != 1 ? 's' : ''));
  42.  
  43.     $ret = array();
  44.     while (count($ret) < $precision && ($item = array_shift($stack)) !== null) {
  45.         if ($item[0] > 0)
  46.             $ret[] = "{$item[0]} {$item[1]}";
  47.     }
  48.  
  49.     return implode(', ', $ret);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement