I would like to sum just the times that does not repeat in a day, see the picture in the link below to understand better
http://postimage.org/image/ew50dnlw/
The total time should be 5 hours
I don't want to count twice the yellow area because another ti开发者_运维技巧me already filled that time
thanks!!
Using the idea proposed by Andre in above answer I could achieve the goal with the code below: Note: To get this working properly don't forget to order your times by start time ASC
<?php
// Function to sum times
function sum($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time) {
list($hour, $minute, $second) = explode(':', $time);
$seconds += $hour * 3600;
$seconds += $minute * 60;
$seconds += $second;
}
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
// Function to subtract times
function sub($end, $start) {
$end = strtotime($end);
$start = strtotime($start);
$seconds = $end - $start;
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
// Some values to work on
// To get this working the times should be ordered by start time ASC
$start = array(
'11:00:00',
'13:00:00',
'14:00:00',
'15:00:00',
);
$end = array(
'12:30:00',
'14:30:00',
'16:00:00',
'16:30:00',
);
$total = "00:00:00";
$tmp = "00:00:00";
for ($i = 0; $i <= count($start); $i++) {
$start_t = $start[$i];
$end_t = $end[$i];
if ($start_t >= $tmp) {
$total = sum(sub($end_t, $start_t), $total);
$tmp = $end_t;
} else {
if ($end_t > $tmp) {
$total = sum(sub($end_t, $tmp), $total);
$tmp = $end_t;
} else {
}
}
}
echo $total;
I did something similar to that, but using Telerik's RadScheduler, so I can't provide you code but describe the logic.
I'll assume you already have those appointments in an array, ordered by start date
First run:
- Get the first appointment
- Read start time
- Read end time
- Sum difference to a variable
Subsequent runs:
- Get the next appointment
- Read start time
- Read end time
- Compare this start date with previous end date
- If it's smaller (they interpolate), sum difference between this end time with previous end time
- Else (they don't interpolate), sum difference between this end time with this start time
Please provide your code, so I can help you better
精彩评论