title: PHP calculate difference in time
body: <p>I've the following code for calculation the difference in time</p>
  
  <pre><code>$estimated_time = '40:30';
  $completed_time = '20:45';
  
  // list the times
  list($hours1, $minutes1) = explode(':', $estimated_time);
  list($hours2, $minutes2) = explode(':', $completed_time);
  
  // mktime
  $t1 = mktime($hours1, $minutes1); // estimated time
  $t2 = mktime($hours2, $minutes2); // completed time
  
  // Calc the difference in seconds
  $seconds = $t1 - $t2;
  // hours
  $hours     =  floor($seconds / (60*60));
  // minutes
  $minutes   =  floor(($seconds / 60) % 60);
  
  // result 19:45
  echo $diff = $hours . ':' . $minutes;
  </code></pre>
  
  <p>This calculation works because 19:45 is expected. The problem is when i change the time like this</p>
  
  <pre><code>// expected 4:30 extra hours but result is -5:30
  // this is caused by the floor method but if I remove the floor
  // method the positive value is not working correctly
  $estimated_time = '40:00';
  $completed_time = '44:30';
  </code></pre>
  
  <p>The result is -5:-30. This is caused be the floor. How could this works correctly with positive and negative values. Also is this a correct way to calculate with times.</p>
  
  <p>I have tried to use DateTime but it could not handles hours greater then 24</p>
  
  <p>SOLVED
  Thx to @Mad Dog <a href="https://stackoverflow.com/questions/40741849/php-calc-difference-between-time-greater-than-24-hours">PHP calc difference between time greater than 24 hours</a></p>
  
  <pre><code>$estimated_time = '40:30';
  $completed_time = '20:55';
  
  // invert
  // 0 =&gt; positive
  // 1 =&gt; negative
  
  // list the times
  list($hours1, $minutes1) = explode(':', $estimated_time);
  list($hours2, $minutes2) = explode(':', $completed_time);
  
  $date1 = new DateTime('now', new DateTimeZone('UTC'));
  $date2 = new DateTime('now', new DateTimeZone('UTC'));
  $time1 = new DateInterval('PT'.$hours1.'H'.$minutes1.'M');
  $time2 = new DateInterval('PT'.$hours2.'H'.$minutes2.'M');
  
  $date1-&gt;add($time1);
  $date2-&gt;add($time2);
  
  $diff = $date2-&gt;diff($date1);
  $result = ($diff-&gt;days * 24 + $diff-&gt;h) . $diff-&gt;format(':%I');
  
  if($diff-&gt;invert == 0){
      echo $result;
  } else {
      echo 0 . ' (extra time: '.$result.')';
  }
  </code></pre>