开发者

More complex sum of time in PHP or Doctrine

开发者 https://www.devze.com 2023-03-02 03:36 出处:网络
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

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:

  1. Get the first appointment
  2. Read start time
  3. Read end time
  4. Sum difference to a variable

Subsequent runs:

  1. Get the next appointment
  2. Read start time
  3. Read end time
  4. Compare this start date with previous end date
  5. If it's smaller (they interpolate), sum difference between this end time with previous end time
  6. 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

0

精彩评论

暂无评论...
验证码 换一张
取 消