PHP - Calculation of inaccessible hours in a calendar / agenda

I have a problem that seems rather difficult to solve, so I hope someone will have a good solution for me :)

I have a PHP program with a reservation list for many hotel conference rooms. I need to calculate how much time at least 1 conference room is used during the day.

Here is an example:

Room 1: 10h 00 to 13h 00  
Room 2: 11h 00 to 14h 00  
Room 3: 15h 00 to 16h 00  

With abstract numbers I need to calculate that the hotel is used for 5 hours (from 10 to 14 hours and from 15 hours to 16 hours).

In the end, it tells me how many hours the hotel has to pay someone to check the rooms in case someone has a problem.

If you don't have a library that can help me, the algorithm may be a good start.

+3
2

:

  • .
  • , . , . - .
  • , , .

:

<?php
// assuming hh:mm format for all the dates //
$intervals = array(
    array(
        'start' => '15:30',
        'end' => '16:00',
    ),
    array(
        'start' => '10:00',
        'end' => '13:00',
    ),
    array(
        'start' => '15:00',
        'end' => '16:09',
    ),
    array(
        'start' => '11:00',
        'end' => '14:00',
    ),
);

// 1. sort the intervals by start date //
function mySortIntervals($a, $b){
    return $a > $b;
}
usort($intervals, 'mySortIntervals');

// 2. merge adjoining intervals //
$active = 0;
$current = 1;
$length = count($intervals);
while($current < $length){
    if($intervals[ $current ]['start'] <= $intervals[ $active ]['end']){
        $intervals[ $active ]['end'] = max($intervals[ $active ]['end'], $intervals[ $current ]['end']);
        unset($intervals[ $current ]);
    }
    else{
        $active = $current;
    }
    $current++;
}

// 3. cout the total time //
$time = 0;
foreach($intervals as $interval){
    $time += strtotime($interval['end']) - strtotime($interval['start']);
}

// output //
echo str_pad((int) ($time/60/60), 2, '0', STR_PAD_LEFT).':';
echo str_pad((int) (($time/60)%60), 2, '0', STR_PAD_LEFT);
?>
+2

, , 15 . ? , , , - .

15 ( - ).

  • ( ). , .
  • ( ) , .

, (00 til 23) (00; 15; 30; 45;)

-. , . .

, , - , .

0

Source: https://habr.com/ru/post/1778335/


All Articles