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... :)

2 Answers 2

19

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.

0
6
<?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';
?>
4
  • 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, 2018 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, 2020 at 21:24
  • $minutes1 - $minutes2 appears to be backwards. Perhaps you intended to take the absolute value?
    – Ryan M
    Apr 23, 2022 at 0:10
  • Note: this would not take DST changes into account, as the other answer does.
    – Ryan M
    Apr 23, 2022 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.