0

I am currently getting the difference between two times in minutes like this below, and it works fine...

$time1 = strtotime($firsttime);
$time2 = strtotime($secondtime);
$interval  = abs($time2 - $time1);
$diffinminutes   = round($interval / 60);

But say for example...

$firsttime = 02:05
$secondtime = 20:05

This calculation would return 1080 minutes (18 hours x 60 minutes).

I would like to be able to get the shortest difference, based on the time being a connected circle (i.e. like a clock haha).

So in the example above, I would rather it "go backwards" from 02:05 until it hit 20:05 and thus return 360 minutes (6 hours x 60 minutes).

In other words, I'm looking to get the shortest difference, regardless of which direction we go to find it.

Hopefully this makes sense.

Any insight on how to accomplish this would be appreciated, thank you!

user3304303
  • 1,027
  • 12
  • 31

1 Answers1

1

(This assumes your inputs are just times and not timestamps.)

If your result is greater than 12 hours, then just subtract it from 24:

if ($result > 720) {
    $result = 1440 - $result;
}

You might want to change the > to >= depending on which side you want ties to fall on.

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98