How to Calculate Number of Working/Business Days Between Two Dates in PHP?

Problem:

You want to find out number of working days between two dates except those holidays – Saturday and Sunday.

Solution:

To calculate the number of days between two dates, follow the steps below-

  • First, convert each date to its equivalent timestamp. (The timestamp of a date is the number of seconds since January 1 1970 00:00:00 UTC to that date.)·
  • Then, we’ll run a loop between the two timestamp to get each day.
  • In the loop, we’ll check whether the date is a working day or not. If it is, we’ll add it.

The following example show how it works-

<?php
$startDate = "2014-06-03";
$endDate = "2014-06-26";
$workingDays = 0;

$startTimestamp = strtotime($startDate);
$endTimestamp = strtotime($endDate);

for($i=$startTimestamp; $i<=$endTimestamp; $i = $i+(60*60*24) ){
if(date("N",$i) <= 5) $workingDays = $workingDays + 1;
}
echo "Total number of working days between $startDate and $endDate is: " . $workingDays . " day(s).";
?>

[wpdm_file id=155]

Output:
Total number of working days between 2014-06-03 and 2014-06-26 is: 18 days.

How it works:

Line 2 $startDate variable holds the beginning date
Line 3 $endDate variable holds the last date
Line 4 We’ll store working days in $workingDays variable. Here, we just initialize the variable.
Line 6 Here, we convert the start date to its timestamp, $startTimestamp using strtotime() function
Line 7 Here, we convert the end date to its timestamp, $endTimestamp.
Line 9-11 The for loop starts from the beginning date and ends at end date. The loop increments by one day. Note that (60*60*24) seconds is equal to 1 day.
Line 10 The character format “N” in the date() function returns numeric representation of a day in the week. So, when it returns 1, that means Monday; similarly, 7 is for Sunday. As 6 and 7 represents for Saturday and Sunday, and we don’t want to calculate those days, we’re considering working days which are equal to or less than 5 and then, adding in the $workingDays variable.
Line 11 At last, we print the total number of working day.