I have made a code to calculate the difference in hours between two dates, but I have a problem, holidays are still being calculated.
i want to calculate the difference without following the holidays
here is my code
date_default_timezone_set('Asia/Jakarta');
$start_date = date_create("2023-08-18 00:00:00");
$end_date = date_create("2023-08-21 00:00:00");
$different = date_diff( $start_date, $end_date );
$day = $different->d;
$hour = $different->h;
$minute = $different->i;
if($hour < 10){
$this_hour = "0".$hour;
} else {
$this_hour = $hour;
}
if($minute < 10){
$this_minute = "0".$minute;
} else {
$this_minute = $minute;
}
if($day < 1){
$result = $this_hour.":".$this_minute;
} elseif($day >= 1) {
$total_hour = ($day * 24) + $this_hour;
$result = $total_hour.":".$this_minute;
}
echo $result;
//Outpput is = 72:00
i have tried the code above, but i want the result not to count holidays. Thanks.
2
Answers
Here is example:
I have added this
$holidays = array("2023-08-19");
for the example. You have to add your holiday days in this array.This a more correct edit.
To calculate the difference in hours between two dates while excluding holidays, you can iterate through the dates between the start and end dates and skip counting the hours on holiday dates. Here’s the modified code:
In this code, I iterated through each day between the start and end dates. For each day, check if it’s not a holiday before adding 24 hours to the total duration. After iterating through all days, we add the remaining hours and minutes from the original calculation. The result will be the difference in hours between the two dates, excluding hours on holiday dates.