Calculate the number of business days between two dates - PHP

Is there a simple function in PHP to calculate the number of business days between two dates ? I would like to calculate business days excluding weekends, national days and public holidays.
17 Jul 2020 at 04:20 PM
0pnshow more
onefiveonefive
Hi,

You can use the solution below to calculate the number of business days between two dates. The function works with date format YYYY-MM-DD. Holidays and national days have to be added to $holidays array. When starting date is the same as end date, the function will return zero business days.



function calculateBusinessDays($startDate,$endDate) {

if ( strtotime($endDate) >= strtotime($startDate) ) {

$holidays = array("2020-12-24","2020-12-25","2020-12-26");
$date = $startDate;
$days = 0;

while ($date != $endDate) {
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
$weekday = date("w", strtotime($date));
if ( $weekday != 6 AND $weekday != 0 AND !in_array($date, $holidays) ) $days++;
}

return $days;
}
else {
return "Please check the dates.";
}

}

echo calculateBusinessDays("2020-07-14","2020-07-17");



The function will calculate, that difference between 2020-07-14 and 2020-07-17 is 3 business days.
19 Jul 2020 at 04:53 PM
0pnshow more
TimTim
Share on FacebookShare on TwitterShare on LinkedInSend email
Follow us on Facebook & Twitter
2022 AnswerTabsTermsContact us