GMR
GMR

Reputation: 111

Difference between two dates in hours not including holidays and weekends

I pieced together a function that will find me the difference between two dates in hours using PHP. However, I am running into a problem where it will add additional hours if the total difference is less than 24 hours.

For example, if I wanted to find the difference in hours between 2017-12-23 00:30:00 and 2017-12-26 12:00:00. It will return a result of 36 hours. I assumed this was because I was using $days = 0; in my for each.

Removing it resolved the issue but had the opposite effect when the range was greater than 24 hours. What am I missing? Should I create an if statement to set $days to -1 when the number of hours is less than 24? Am I taking the long way around the bus?

<?php
function number_of_working_hours($from, $to) {
    $workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...)
    $holidayDays = ['*-12-25', '*-01-01']; # variable and fixed holidays

    $from = new DateTime($from);
    $to = new DateTime($to);
    $to->modify('+1 day');
    $interval = new DateInterval('PT1H');
    $periods = new DatePeriod($from, $interval, $to);
    $days = 0;
    foreach ($periods as $period) {
        if (!in_array($period->format('N'), $workingDays)) continue;
        if (in_array($period->format('Y-m-d'), $holidayDays)) continue;
        if (in_array($period->format('*-m-d'), $holidayDays)) continue;
        $days++;
    }
    return $days;
}
echo number_of_working_hours('2017-12-23 00:30:00', '2017-12-26 12:00:00');
?>

Upvotes: 1

Views: 474

Answers (1)

retrowaver
retrowaver

Reputation: 66

It seems to work if you remove $to->modify('+1 day'); line, which I guess has no reason to be there.

echo number_of_working_hours('2017-12-23 00:30:00', '2017-12-26 12:00:00'); //12
echo number_of_working_hours('2017-12-15 15:00:00', '2017-12-18 12:00:00'); //21
echo number_of_working_hours('2017-12-11 15:00:00', '2017-12-13 12:00:00'); //45

Upvotes: 1

Related Questions