How to Calculate Business Days in PHP?

We have given two dates, our task is to write a PHP program to get total business days, i.e. weekdays between the two dates.

Below are the approaches to calculate business days in PHP:

Table of Content

  • Using DateTime and DateInterval
  • Using strtotime and date functions

Using DateTime and DateInterval

In this approach, we are using the DateTime class in PHP to handle date calculations. By iterating through each day between the start and end dates and checking if it falls on a weekday (Monday to Friday), we count the number of business days. The DateInterval class helps increment the date by one day in each iteration, ensuring accurate business day calculations.

Example: The below example uses DateTime and DateInterval to calculate business days in PHP.

PHP
<?php
function getBusinessDays1($startDate, $endDate) {
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    $businessDays = 0;
    while ($start <= $end) {
        $dayOfWeek = $start->format('N');
        if ($dayOfWeek < 6) {
            $businessDays++;
        }
        $start->add(new DateInterval('P1D'));
    }
    return $businessDays;
}
$startDate = '2024-05-01';
$endDate = '2024-05-10';
echo "Business days: "
  . getBusinessDays1($startDate, $endDate);
?>

Output
Business days: 8

Using strtotime() and date() functions

In this approach, we are using PHP’s strtotime and date functions to calculate business days. By converting the start and end dates into Unix timestamps, we iterate through each day, checking if it’s a weekday (Monday to Friday) using the date function. The strtotime(‘+1 day’, $currentDate) increments the date by one day in each iteration, allowing us to count the number of business days properly.

Example: The below example uses strtotime and date functions to calculate business days in PHP.

PHP
<?php
function getBusinessDays2($startDate, $endDate) {
    $businessDays = 0;
    $currentDate = strtotime($startDate);
    $endDate = strtotime($endDate);
    while ($currentDate <= $endDate) {
        $dayOfWeek = date('N', $currentDate);
        if ($dayOfWeek < 6) {
            $businessDays++;
        }
        $currentDate = strtotime('+1 day', $currentDate);
    }
    return $businessDays;
}
$startDate = '2024-05-01';
$endDate = '2024-05-10';
echo "Business days: " 
. getBusinessDays2($startDate, $endDate);
?>

Output
Business days: 8