HenerH
HenerH

Reputation: 19

Difference between two times (without date) in PHP

I know there are a lot same kind problems but nothing do what I need.

I have two times in the form of H.MM (3.25 - thats not 3:25, its 3:15) or HH.MM (22.75 - so its 22:45).

I need to calculate the difference between starttime and endtime in hours. And i don't have date.

My times are (so you can check):

  1. 15.25 -> 23.75
  2. 10.0 -> 22.0
  3. 22.5 -> 8.0
  4. 20.0 -> 10.0
  5. 9.0 -> 17.0
  6. 23.0 -> 6.0

My head is on fire already.

Thank you for helping.

Upvotes: 0

Views: 139

Answers (1)

FuzzyTree
FuzzyTree

Reputation: 32402

$times = array(
    array(15.25,23.75),
    array(10.0,22.0),
    array(22.5,8.0),
    array(20.0,10.0),
    array(9.0,17.0),
    array(23.0,6.0),
);

foreach($times as $time) {

    $end = $time[1];

    if($time[1] < $time[0]) {
        $end += 24;
    }

    $diff = $end - $time[0];
    $hours = floor($diff);
    $minutes = ($diff - $hours) * 60;

    if(strlen($minutes) < 2)
        $minutes .= '0';

    print $time[0] . ' -> ' . $time[1] 
    . " $hours:$minutes\n";
}

Demo

Upvotes: 1

Related Questions