0

I am trying to get the time difference between two dates that considers the holidays and start & end working hours.

Here is my code:

function business_hours($start, $end, $holidays = null){
    $startDate = new DateTime($start);
    $endDate = new DateTime($end);
    $periodInterval = new DateInterval('PT1H');

    $period = new DatePeriod($startDate, $periodInterval, $endDate);
    $count = 0;

    foreach($period as $date){
        #clone $date to get properties
        #set start time of working hours to 8:00
        $startofday = clone $date;
        $startofday->setTime(8,30);

        #clone $date to get properties
        #set end time of working hours to 17:00
        $endofday = clone $date;
        $endofday->setTime(17,30);

        #this will be used for conditional check
        $notHoliday = true;
        
        #now check the array of holiday and check if in range dates is same with holidays we have
        if($holidays != null && is_array($holidays) && in_array($date->format('Y-m-d'), $holidays)){
            $notHoliday = false;
        }
    
        #check if $date is greater than $startofdate and less that the $endofday and does not fall on Saturday or Sunday
        #also check if the hours of date is less than or equal to 12 or greater that 13 and $notHoliday equals true
        if($date > $startofday && $date <= $endofday && !in_array($date->format('l'), array('Saturday', 'Sunday')) && ($date->format('H') <= 12 || $date->format('H') > 13) && $notHoliday){
            $count++;
        }
    }
    
    return $count;
}

My problem with my code is that it does not calculate the minute difference. I would like to include the the minutes calculation in order to get the exact time worked.

  • There are so many examples here on SO, did they not help? Eg https://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php, https://stackoverflow.com/questions/2920335/how-to-calculate-time-difference-in-php, https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php, etc. – Don't Panic Apr 14 '21 at 06:16
  • @Don'tPanic I searched for examples but none of them applied for what I am trying to accomplish –  Apr 14 '21 at 08:54

1 Answers1

0

you can try package Carbon of php, it can substract 2 date and return exactly minutes with method diffInMinutes()

Mòe
  • 269
  • 2
  • 7