How to find out the number of weekly days per month?

I have this problem right now: given the month and year, I need to know how many days she has (i.e. the number of days, excluding Saturday and Sunday).

It seems so simple, and yet I am puzzled. Of course, I could solve this with a for loop and check if it’s not a day or a Saturday, but if you don’t increase the counter, but that’s just silly (and linear time), given that I’m sure I can get away with a few ticks or modules .

Any idea of ​​an algorithm? You have all the features of PHP 4.4.1 at your disposal.


EDIT Here's a working implementation of the for loop:

 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; } 
+4
source share
3 answers

Just check weekday 29, 30 and 31 (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; } 
+3
source

You could find the first and last Sunday of the year, and then divide the difference in the days of the two dates with 7. Do the same on Saturday, and then you can subtract the number of Sundays and Saturdays from the total number of days in the year. This is the most effective solution I have found so far.

0
source

Found this solution without a loop (unverified 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; } 
0
source

Source: https://habr.com/ru/post/1339276/


All Articles