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
calculateWorkingDaysInMonth(2010,04);
is going to result in 22.
Nice! :)
You might also enjoy:
-
Picked this cool little PHP function to calculate and return the last day of a month for any year off the always informative lutrov interactive website the ...
-
Seeing as I'm currently so busy implementing datepickers and such at work at the moment, here's a nifty little bit jQuery/Javascript code that I whipped up ...
-
Wow, stumbled across this extremely clever, one line of PHP code to return the correct number of days for any given month, courtesy of the extremely talente ...
-
A big headache for developers, particularly when it comes to database-driven applications, is the differing date formats across country borders, a classic e ...
-
If you are working on an Ubuntu server installation that comes in the command line only variation, you might at any point in time want to see just what exac ...