Skip to content

Instantly share code, notes, and snippets.

@willemwollebrants
Last active December 17, 2019 19:21
Show Gist options
  • Save willemwollebrants/5efc58664c16b99705a7 to your computer and use it in GitHub Desktop.
Save willemwollebrants/5efc58664c16b99705a7 to your computer and use it in GitHub Desktop.
Given multiple periods of time in a day, that may overlap, calculate the sum of all the periods, in hours.
<?php
//24 hours in one day, plus an extra hour to count any minutes past midnight
$totals = array_fill_keys(range(0, 24), array_fill_keys(range(0, 59), 0));
//loop through the ranges
foreach ($ranges as $range) {
$start = (int) $range[0]->format('H');
//the duration of this range
$delta = $range[1]->diff($range[0]);
//the minutes
$start_range = array_fill_keys(range((int) $range[0]->format('i'), 59), 1);
$totals[$start] = $start_range + $totals[$start];
for ($a = 1; $a < $delta->h; $a++) {
$totals[$start + $a] = array_fill_keys(range(0, 59), 1);
}
$end_range = array_fill_keys(range(1, (int) $range[1]->format('i')), 1);
$totals[$start + $a] = $end_range + $totals[$start + $a];
}
$hours = 0;
$minutes = 0;
foreach ($totals as $total) {
$duration = array_sum($total);
//if duration is 60 seconds or more, this hour is full
if ($duration >= 60) {
$hours += 1;
} else {
//otherwise, count the minutes
$minutes += $duration;
}
}
//if we have over 60 seconds of spare minutes, these are also hours
$hours += intval($minutes / 60);
$minutes = $minutes % 60;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment