PHP: Calculate the Number of Working Days in a Month CodeUnit 23 APR 2010

How to calculate the number of working days in a month, in other words discount Saturdays and Sundays from a month’s total number of days.

It sounds pretty simple, but because of the shifting nature of the calendar we use, one can’t just take a guess and average it you know. No, we need a function to work out this total for each month of any particular year.

Now of course I’m sure there are for more acute, beautiful or elegant solutions to this particular problem out there, but I for one quite like the idea of seeing the logic behind what is happening step by step, which is exactly why I came up with this little function to do the work for me.

So in order to calculate the number of working days in a month by removing Saturdays and Sundays from its day count, have a look at this simple PHP function:

function calculateWorkingDaysInMonth($year = '', $month = '')
	//in case no values are passed to the function, use the current month and year
	if ($year == '')
		$year = date('Y');
	if ($month == '')
		$month = date('m');
	//create a start and an end datetime value based on the input year 
	$startdate = strtotime($year . '-' . $month . '-01');
	$enddate = strtotime('+' . (date('t',$startdate) - 1). ' days',$startdate);
	$currentdate = $startdate;
	//get the total number of days in the month	
	$return = intval((date('t',$startdate)),10);
	//loop through the dates, from the start date to the end date
	while ($currentdate <= $enddate)
		//if you encounter a Saturday or Sunday, remove from the total days count
		if ((date('D',$currentdate) == 'Sat') || (date('D',$currentdate) == 'Sun'))
			$return = $return - 1;
		$currentdate = strtotime('+1 day', $currentdate);
	} //end date walk loop
	//return the number of working days
	return $return;

As you can see, the logic of the function is pretty straightforward to follow. To use the function in your code, simply call it and pass the month and year you want it to examine, meaning that


is going to result in 22.

Nice! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.