zneak
zneak

Reputation: 138261

How can I figure out the number of week days in a month?

I'm having this problem right now: given a month and a year, I'd need to know how many week days it has (that is, the number of days excluding Saturday and Sunday).

It seems so simple, and yet I'm baffled. Of course I could solve it with a for loop and check if the day's a Saturday or a Sunday, and if not increment a counter, but this is just plain stupid (and linear time) considering I'm pretty sure I could get away with a couple of divisions or modulos.

Any idea of the algorithm? You have all the power of PHP 4.4.1 at your disposal.


EDIT Here's a working for loop implementation:

function weekdays_in_month($month, $year)
{
    $days_in_month = days_in_month($month); // days_in_month defined somewhere
    $first_day = date('w', mktime(0,0,0, $month, 1, $year));
    $counter = 0;
    for ($i = 0; $i < $days_in_month; $i++)
    {
        if (($first_day + $i + 1) % 7 >= 2)
            $counter++;
    }
    return $counter;
}

Upvotes: 4

Views: 236

Answers (3)

John
John

Reputation: 16007

Just check the weekday-ness of the 29th, 30th, and 31st (if these dates exist).

Add 20.

Editing your function:

function weekdays_in_month($month, $year)
{
    // NOTE: days_in_month needs $year as input also, to account for leap years
    $days_in_month = days_in_month($month, $year); // days_in_month defined somewhere
    $first_day = date('w', mktime(0,0,0, $month, 1, $year));
    $counter = 20;  // first 28 days of month always have 20 weekdays
    for ($i = 28; $i < $days_in_month; $i++)
    {
        if (($first_day + $i + 1) % 7 >= 2)
            $counter++;
    }
    return $counter;
}

Upvotes: 3

bauc
bauc

Reputation: 1

Found this solution without for loop (untested from http://www.phpbuilder.com/board/archive/index.php/t-10267313.html)

function weekdays_in_month($month, $year)
{
$first = mktime(0,0,1,$month,1,$year);
// The first day of the month is also the first day of the
// remaining days after whole weeks are handled.
list($first_day,$days) = explode(' ',date('w t',$first));
$weeks = floor($days/7);
$weekdays = $weeks*5;
$remaining_days = $days-$weeks*7;

if($remaining_days==0)
return $weekdays; // Only happens most Februarys

$weekdays += $remaining_days-1;
// Neither starts on Sunday nor ends on Saturday
if($first_day!=0 && ($first_day+$days-1)%7!=6)
{ // Adjust for weekend days.
$weekdays += ($remaining_days<=(6-$first_day))-
($remaining_days>(6-$first_day));
}


return $weekdays;
}

Upvotes: 0

Mato
Mato

Reputation: 830

You could search for the first and the last sunday in the year and then divide the difference in days of those two dates with 7. Do the same thing for saturday and then you can subtract the number of sundays and saturdays from tho total number of days in the year. That is the most efficient solution I have found so far.

Upvotes: 0

Related Questions