Most spreadsheet programs have a rather nice little built-in function called NETWORKDAYS to calculate the number of business days (i.e. Monday-Friday, excluding holidays) between any two given dates. I couldn't find a simple way to do that in PHP, so I threw this together. It replicates the functionality of OpenOffice's NETWORKDAYS function - you give it a start date, an end date, and an array of any holidays you want skipped, and it'll tell you the number of business days (inclusive of the start and end days!) between them.
I've tested it pretty strenuously but date arithmetic is complicated and there's always the possibility I missed something, so please feel free to check my math.
The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. "skip all Fridays and Saturdays but include Sundays") or to set up dates that should always be skipped (e.g. "skip July 4th in any year, skip the first Monday in September in any year"). But that's a project for another time.
<?php
function networkdays($s, $e, $holidays = array()) {
if ($s > $e)
return networkdays($e, $s, $holidays);
$sd = date("N", $s);
$ed = date("N", $e);
$w = floor(($e - $s)/(86400*7)); if ($ed >= $sd) { $w--; } $nwd = max(6 - $sd, 0); $nwd += min($ed, 5); $nwd += $w * 5; foreach ($holidays as $h) {
$h = strtotime($h);
if ($h > $s && $h < $e && date("N", $h) < 6)
$nwd--;
}
return $nwd;
}
$start = strtotime("1 January 2010");
$end = strtotime("13 December 2010");
$holidays = array();
$holidays[] = "4 July 2010"; $holidays[] = "6 September 2010"; echo networkdays($start, $end, $holidays); ?>
Or, if you just want to know how many work days there are in any given year, here's a quick function for that one:
<?php
function workdaysinyear($y) {
$j1 = mktime(0,0,0,1,1,$y);
if (date("L", $j1)) {
if (date("N", $j1) == 6)
return 260;
elseif (date("N", $j1) == 5 or date("N", $j1) == 7)
return 261;
else
return 262;
}
else {
if (date("N", $j1) == 6 or date("N", $j1) == 7)
return 260;
else
return 261;
}
}
?>