I need to calculate the number of working hours that have expired between two dates. Working hours are 08:30 to 17:30, Monday to Friday.
Here is what I have so far, can anybody see the flaws in my logic? I’m sure it could also be made much more compact and better.
/*You take your start date and calculate the rest time on this day (if it is a business day)
You take your end date and calculate the time on this day and
take the days in between and multiply them with your business hours (just those, that are business days)
Day start is 08:30 and day end is 17:30 so 9 hour working days*/
function biss_hours($start, $end){
$startDate = new DateTime($start);
$endDate = new DateTime($end);
//Set the start and end dates to the start of the working day
$startofday = clone $startDate;
$startofday->setTime(8,30);
$enddaystart = clone $endDate;
$enddaystart->setTime(8,30);
//get the rest time on start day in hours
$t1 = $startofday->format('Y-m-d H:i:s');
$t2 = $startDate->format('Y-m-d H:i:s');
$firstDayRest = calculate_hours($t1, $t2);
//get the rest time on start day in hours
$t3 = $enddaystart->format('Y-m-d H:i:s');
$t4 = $endDate->format('Y-m-d H:i:s');
$lastDayRest = calculate_hours($t3, $t4);
//Get the number of days between the two dates
$daysBetween = getWeekdayDifference($start, $end);
//multiply the days by the 9 working hours
$hoursBetween = $daysBetween * 9;
//add the rest times onto the number of working hours between the two dates.
return $hoursBetween + $firstDayRest + $lastDayRest;
}
//returns the hours between two dates
function calculate_hours($t1, $t2){
$t1 = StrToTime ($t1);
$t2 = StrToTime ($t2);
$diff = $t2 - $t1;
$hours = $diff / ( 60 * 60 );
return $hours;
}
//returns the number of days (excluding weekends) between two dates
function getWeekdayDifference($startDate, $endDate)
{
$days = 0;
$startDate = new DateTime($startDate);
$endDate = new DateTime($endDate);
while($startDate->diff($endDate)->days > 0) {
$days += $startDate->format('N') < 6 ? 1 : 0;
$startDate = $startDate->add(new \\DateInterval("P1D"));
}
return $days;
}
$start = '2014-06-25 11:30';
$end = '2014-07-22 12:30';
echo $onHold = biss_hours($start, $end);