0

I have two variables, $from and $to.

$from is 08:00:00 and $to is 10:00:00. How can I get the difference between them in hours?

For example in the above case, I want to get only 2.

Thanks.

Hienz
  • 688
  • 7
  • 21
  • Possible duplicate of [get the difference in time between two given time](https://stackoverflow.com/questions/36758892/get-the-difference-in-time-between-two-given-time) – Nick Apr 28 '18 at 13:34
  • Trust me, you want to use `DateTime` and `diff()`. *Some* of the troubles you'll avoid, I detailed in https://stackoverflow.com/a/31196355/1428679 . *For me it's too late, but you can still save yourself!* :-D – LSerni Apr 28 '18 at 14:01

2 Answers2

2
$from = "08:00:0";
$to = "10:00:00";

$start_datetime = new DateTime(date('Y-m-d').' '.$from);
$end_datetime = new DateTime(date('Y-m-d').' '.$to);

$timeDiff=$start_datetime->diff($end_datetime);

echo $hour = $timeDiff->format('%h hours');
echo $min = $timeDiff->format('%i min');
echo $sec = $timeDiff->format('%s sec');
jvk
  • 2,133
  • 3
  • 19
  • 28
0

Actually I was doing it right, I had some other code issues.. If someone needs it though:

$hour = (strtotime($to) - strtotime($from)) / 3600;

Hienz
  • 688
  • 7
  • 21
  • This will fail when you happen to hit daylight saving time boundaries in whatever default time zone your PHP installation is configured to use. But I guess is should be robust enough if you specify UTC. – Álvaro González Apr 28 '18 at 13:35