Get Difference Between 2 Dates Using PHP

Filed Under (General) by Wenbert on 22-10-2007

Tagged Under : ,

Here is how to get the difference between two dates in PHP.

  1.  
  2. public static function toTimestamp($date){
  3.     $arrayDate=self::toArray($date);
  4.     return mktime($arrayDate[‘hour’],$arrayDate[‘minute’],$arrayDate[’second’],$arrayDate[‘month’],$arrayDate[‘day’],$arrayDate[‘year’]);
  5. }
  6.  
  7. public static function dateDiff($date1,$date2,$unit=‘HOUR’){
  8.     $date1=self::toTimestamp($date1);
  9.     $date2=self::toTimestamp($date2);
  10.            
  11.     $secs=$date1-$date2;
  12.    
  13.     switch(strtoupper($unit)){
  14.         case ‘WEEK’:return $secs/60/60/24/7; break;
  15.         case ‘DAY’:return $secs/60/60/24; break;
  16.         case ‘HOUR’:return $secs/60/60; break;
  17.         case ‘MINUTE’:return $secs/60; break;
  18.         case ‘SECOND’:return $secs; break;
  19.         default:return $secs/60/60; break;
  20.     }
  21. }
  22.  

Usage:

  1.  
  2. DateFormat::dateDiff($current_tr->requisition_dateTo,$current_tr->requisition_dateFrom,"DAY"));
  3.  

The static function example above is from an MVC Framework. But you can edit it the sample code to fit your needs.
This tutorial is documented here.

Leave a Reply