Web based solutions, tutorials, examples and help. 

  • [ Function ] PHP Time Difference

 #42  by Nito
 Tue Nov 09, 2010 5:01 am
This function is used to check the difference between two time's (you can use regular DATE, or UNIX time stamps and convert them over to date's, as I have in this example). It will then put the times into human format, which is useful for forums, blogs and a wide variety of social websites.

Function:
Code: Select allfunction chkDif($a) {
   $a = round($a,0);
   if($a <= 59) { $b = 'just now'; }
   if($a >= 59 && $a <= 3599) {
      $b = ($a / 60);   
      $c = ' minute';
   }
   if($a >= 3600 && $a <= 86399) {
      $b = (($a / 60) / 60);
      $c = ' hour';
   }
   if($a >= 86400 && $a <= 604799) {
      $b = ((($a / 60) / 60) / 24);
      $c = ' day';
   }
   if($a >= 604800 && $a <= 2629742) {
      $b = (((($a / 60) / 60) / 24) / 7);
      $c = ' week';
   }
   if($a >= 2629743 && $a <= 31556925) {
      $b = ((((($a / 60) / 60) / 24) / 7) / 4);
      $c = ' month';
   }
   if($a >= 31556926) {
      $b = (((((($a / 60) / 60) / 24) / 7) / 4) / 12);
      $c = ' year';
   }
   $b = round($b,0);
   if($b != 'just now') {
      $b > 1 ? $d = $b.$c.'s ago' : $d = $b.$c.' ago';
      return $d;
   } else {
      return $b;
   }
}


Usage:
Code: Select all$chkDif= strtotime(date("Y-m-d h:i:s")) - strtotime(date("Y-m-d h:i:s", $FetchAColumn->db_stored_time));
echo chkDif($chkDif)';


Enjoy. =)

[/EDIT]
It will return 0 if the times are both the same, so the usage should be changed to the following:
Code: Select allif(strtotime(date("Y-m-d h:i:s")) == strtotime(date("Y-m-d h:i:s", $FetchAColumn->db_stored_time))) {
echo 'Just Now';
} else {
$chkDif= strtotime(date("Y-m-d h:i:s")) - strtotime(date("Y-m-d h:i:s", $FetchAColumn->db_stored_time));
echo chkDif($chkDif)';
}
 #43  by Nito
 Tue Nov 16, 2010 7:39 am
Here is another way to find the time difference, and output it into human lingo.

Function:
Code: Select allfunction relativeTime($dt,$precision=2) {
   $times=array(   365*24*60*60   => "year",
               30*24*60*60      => "month",
               7*24*60*60      => "week",
               24*60*60      => "day",
               60*60         => "hour",
               60            => "minute",
               1            => "second");   
   $passed=time()-$dt;   
   if($passed<5) { $output='less than 5 seconds ago'; }
   else {
      $output=array();
      $exit=0;      
      foreach($times as $period=>$name) {
         if($exit>=$precision || ($exit>0 && $period<60)) break;
         $result = floor($passed/$period);
         if($result>0) {
            $output[]=$result.' '.$name.($result==1?'':'s');
            $passed-=$result*$period;
            $exit++;
         }
         else if($exit>0) $exit++;
      }
      $output=implode(' and ',$output).' ago';
   }
   return $output;
}


Example Usage:
Code: Select all echo relativeTime(date('r',mktime()))