Skip to content

Instantly share code, notes, and snippets.

@TemporaryJam
Last active January 2, 2016 09:39
Show Gist options
  • Save TemporaryJam/8284866 to your computer and use it in GitHub Desktop.
Save TemporaryJam/8284866 to your computer and use it in GitHub Desktop.
Calculate working days between dates
$nr_work_days = getWorkingDays('2014-05-01','2014-05-06', null);
echo $nr_work_days;
/**
* Calculate the number of working days between two dates.
* Note: The result is inclusive of the start and end date. Given two adjacent weekday dates the result is 2
* Return 0 if the start date is greater than the end date
* @param string $startDate Starting date
* @param string $endDate End date
* @param array $additional_holidays Additional holidays to remove from the calculation
* @return int Number of working days
*/
function getWorkingDays($startDate, $endDate, $additional_holidays=array()){
$bank_holidays = $holidays = array(
'2014-04-18', // Good Friday
'2014-04-21', // Easter Monday
'2014-05-05', // Early May bank holiday
'2014-05-26', // Spring bank holiday
'2014-08-25', // Summer bank holiday
'2014-12-25', // Christmas day
'2014-12-26', // Boxing day
'2015-01-01', // New Year's Day
'2015-04-03', // Good Friday
'2015-04-06', // Easter Monday
'2015-05-04', // Early May bank holiday
'2015-05-25', // Spring bank holiday
'2015-08-31', // Summer bank holiday
'2015-12-25', // Christmas day
'2015-12-26', // Boxing day
'2016-01-01', // New Year's Day
'2016-03-25', // Good Friday
'2016-03-28', // Easter Monday
'2016-05-02', // Early May bank holiday
'2016-05-30', // Spring bank holiday
'2016-08-29', // Summer bank holiday
'2016-12-25', // Christmas day
'2016-12-26', // Boxing day
'2017-01-01', // New Year's Day
'2017-04-14', // Good Friday
'2017-04-17', // Easter Monday
'2017-05-01', // Early May bank holiday
'2017-05-29', // Spring bank holiday
'2017-08-28', // Summer bank holiday
'2017-12-25', // Christmas day
'2017-12-26', // Boxing day
);
if (count($additional_holidays)) {
$holidays = array_merge($bank_holidays, $additional_holidays);
}
$begin=strtotime($startDate);
$end=strtotime($endDate);
if ($begin > $end) {
return 0;
} else {
$no_days=0;
$weekends=0;
while ($begin <= $end) {
$no_days++; // no of days in the given interval
$what_day = date("N", $begin);
if ($what_day > 5) { // 6 and 7 are weekend days
$weekends++;
}
$begin+=86400; // +1 day
}
$working_days = $no_days-$weekends;
$begin=strtotime($startDate);
$end=strtotime($endDate);
//subtract holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn't fall in weekend
if ($begin <= $time_stamp && $time_stamp <= $end && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7) {
$working_days--;
}
}
return $working_days;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment