6

I need to calculate the difference between two times in hours. For example, the difference between 08:00:00 and 09:30:00 would be 1.5 hours.

I'm using the code below:

$time1 = '08:00:00';
$time2 = '09:30:00';
$difference = $time2 - $time1;
echo $difference;

Instead of getting 1.5 back as I'd expect, I'm getting 1. I'm sure this is a time formatting issue that someone can easily advise me on. Hopefully... :)

Dingo Bruce
  • 405
  • 1
  • 7
  • 14

3 Answers3

20

You can try my code

<?php
$time1 = strtotime('08:00:00');
$time2 = strtotime('09:30:00');
$difference = round(abs($time2 - $time1) / 3600,2);
echo $difference;

Note: The code above will round to minutes.

Leandro Papasidero
  • 3,728
  • 1
  • 18
  • 33
5
<?php
    $time1 = '08:00:00';
    $time2 = '09:30:00';
    $array1 = explode(':', $time1);
    $array2 = explode(':', $time2);

    $minutes1 = ($array1[0] * 60.0 + $array1[1]);
    $minutes2 = ($array2[0] * 60.0 + $array2[1]);

    echo $diff = $minutes1 - $minutes2.' Minutes';
?>
swathi_sri
  • 417
  • 4
  • 8
  • It's good to have code broken down like this, but it would be good to explain how this resolves the rounding issue in the question. – Taegost Feb 13 '18 at 14:05
  • When you explode the time string it will have a new string, not an array, so this code will cause an error – TheGeeky Oct 18 '20 at 21:24
  • `$minutes1 - $minutes2` appears to be backwards. Perhaps you intended to take the absolute value? – Ryan M Apr 23 '22 at 00:10
  • Note: this would not take DST changes into account, as the [other answer](https://stackoverflow.com/a/29664921/208273) does. – Ryan M Apr 23 '22 at 00:11
0

I suggest use diff to calculate two time difference

$time1 = new DateTime('08:00:00');
$time2 = new DateTime('09:30:00');
$interval = $time1->diff($time2);

echo $interval->format('%H:%I');
Saghachi
  • 851
  • 11
  • 19