Get number of weekdays in a given month
Some basic code:
$month = 12;
$weekdays = array();
$d = 1;
do {
$mk = mktime(0, 0, 0, $month, $d, date("Y"));
@$weekdays[date("w", $mk)]++;
$d++;
} while (date("m", $mk) == $month);
print_r($weekdays);
Remove the @
if your PHP error warning doesn't show notices.
Calculate number of working days in a month
function countDays($year, $month, $ignore) {
$count = 0;
$counter = mktime(0, 0, 0, $month, 1, $year);
while (date("n", $counter) == $month) {
if (in_array(date("w", $counter), $ignore) == false) {
$count++;
}
$counter = strtotime("+1 day", $counter);
}
return $count;
}
echo countDays(2013, 1, array(0, 6)); // 23
The date
function is used in this example. Note about ignore parameter: 0 is sunday, ..., 6 is saturday.
Count of weekdays in a given month
With table, DateTable with a column Date of type Date, the following query will do what you ask.
SELECT
DATENAME(dw, Date) AS WeekDay
,Date
,ROW_NUMBER() OVER (ORDER BY Date) AS Day
FROM DateTable
WHERE DATEPART(dw, Date) NOT IN (1, 7)
ORDER BY Date
How would I get the amount of weekdays in a month with LocalDate - Java
If desired, see optimized brute-force solution at the end
Here is a non-brute-force implementation to calculate week days (Mon-Fri) in a month.
It uses YearMonth
instead of LocalDate
, since the day-of-month value is meaningless to the calculation.
public static int weekDaysInMonth(YearMonth yearMonth) {
int len = yearMonth.lengthOfMonth(); // 28-31, supporting leap year
int dow = yearMonth.atDay(1).getDayOfWeek().getValue(); // 1=Mon, 7=Sun
return (dow <= 5 ? Math.min(len - 8, 26 - dow) : Math.max(len + dow - 16, 20));
}
Here is an overload taking a LocalDate
, so it's easy to call if that's what you have.
public static int weekDaysInMonth(LocalDate date) {
return weekDaysInMonth(YearMonth.from(date));
}
Test
System.out.println(weekDaysInMonth(LocalDate.parse("2018-04-15"))); // April 15, 2018
System.out.println(weekDaysInMonth(YearMonth.of(2018, 5))); // May 2018
Output
21
23
Explanation of Formula
The formula in the return
statement was created by examining the expected return value for every combination of len
(number of days in month, 28 - 31) and dow
(day-of-week of first day of month, 1=Mon - 7=Sun):
| 1 2 3 4 5 6 7
| Mo Tu We Th Fr Sa Su
---+----------------------------
28 | 20 20 20 20 20 20 20
29 | 21 21 21 21 21 20 20
30 | 22 22 22 22 21 20 21
31 | 23 23 23 22 21 21 22
Explanation for dow <= 5
(Mon-Fri)
Initially there are len - 8
weekdays, i.e. we subtract the 4 weekends that always exist in a month.
As we get to Thursday and Friday, we need to cap that for the 1 or 2 weekend days we lose. If you look at the 31-day row, we cap it at 26 - dow
, i.e. for Friday (dow=5
) we cap at 21
, and for Thursday (dow=4
) we cap at 22
. For Monday-Wednesday, we also cap, but cap is equal to or higher than initial calculation, so it doesn't matter.
Capping is done using min(xxx, cap)
method, so we get:
min(len - 8, 26 - dow)
Explanation for dow >= 6
(Sat-Sun)
You can see a small triangle in the lower-right corner. If we extend that pattern, we get:
| 4 5 6 7
---+---------------
28 | 16 17 18 19
29 | 17 18 19 20
30 | 18 19 20 21
31 | 19 20 21 22
As a formula, that is len + dow - 16
.
Comparing that to original grid, numbers bottom out at 20
, which is done using max(xxx, bottom)
method, so we get:
max(len + dow - 16, 20)
Conclusion
Finally we combine the two using ternary conditional operator:
dow <= 5 ? min(len - 8, 26 - dow) : max(len + dow - 16, 20)
Full Java statement is then:
return (dow <= 5 ? Math.min(len - 8, 26 - dow) : Math.max(len + dow - 16, 20));
Brute-Force Solution
If you prefer a brute-force solution, you can ease it by skipping the first 4 weeks that always exists in a month:
public static int weekDaysInMonth(LocalDate refDate) {
LocalDate firstOfMonth = refDate.withDayOfMonth(1);
LocalDate nextMonth = firstOfMonth.plusMonths(1);
int days = 20;
for (LocalDate date = firstOfMonth.plusDays(28); date.isBefore(nextMonth); date = date.plusDays(1))
if (date.getDayOfWeek().getValue() <= 5) // 1=Mon - 5=Fri, i.e. not 6=Sat and 7=Sun
days++;
return days;
}
PHP: getting weekdays numbers of a given month
Not very smart, but would works for you:
// sept. 2012
$month = 9;
// loop through month days
for ($i = 1; $i <= 31; $i++) {
// given month timestamp
$timestamp = mktime(0, 0, 0, $month, $i, 2012);
// to be sure we have not gone to the next month
if (date("n", $timestamp) == $month) {
// current day in the loop
$day = date("N", $timestamp);
// if this is between 1 to 5, weekdays, 1 = Monday, 5 = Friday
if ($day == 1 OR $day <= 5) {
// write it down now
$days[$day][] = date("j", $timestamp);
}
}
}
// to see if it works :)
print_r($days);
Get weekdays within a month
With the help of this answer, I was able to accomplish this.
let calendar = NSCalendar.currentCalendar()
let normalizedStartDate = calendar.startOfDayForDate(NSDate().startOfMonth)
let normalizedEndDate = calendar.startOfDayForDate(NSDate().endOfMonth)
var dates = [normalizedStartDate]
var currentDate = normalizedStartDate
repeat {
currentDate = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: 1, toDate: currentDate, options: .MatchNextTime)!
dates.append(currentDate)
} while !calendar.isDate(currentDate, inSameDayAsDate: normalizedEndDate)
let weekdays = dates.filter { !calendar.isDateInWeekend($0) }
weekdays.forEach { date in
print(NSDateFormatter.localizedStringFromDate(date, dateStyle: .FullStyle, timeStyle: .NoStyle))
}
And it works!
Monday, February 1, 2016
Tuesday, February 2, 2016
Wednesday, February 3, 2016
Thursday, February 4, 2016
Friday, February 5, 2016
Monday, February 8, 2016
Tuesday, February 9, 2016
Wednesday, February 10, 2016
Thursday, February 11, 2016
Friday, February 12, 2016
Monday, February 15, 2016
Tuesday, February 16, 2016
Wednesday, February 17, 2016
Thursday, February 18, 2016
Friday, February 19, 2016
Monday, February 22, 2016
Tuesday, February 23, 2016
Wednesday, February 24, 2016
Thursday, February 25, 2016
Friday, February 26, 2016
Monday, February 29, 2016
How to get a list of week days in a month?
Well, how about:
public static List<DateTime> GetDates(int year, int month)
{
return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
.Select(day => new DateTime(year, month, day))
.Where(dt => dt.DayOfWeek != DayOfWeek.Sunday &&
dt.DayOfWeek != DayOfWeek.Saturday)
.ToList();
}
Related Topics
How to Verify the Requesting Server in PHP
Is There a Difference Between Instantiation with Parentheses or Without
Set_Error_Handler() Doesn't Work for Fatal Error
Php:File_Get_Contents($Loc) Fails
Can't Connect to Postgresql with PHP Pg_Connect()
How to Create PHP Two Column Table with Values from the Database
Phpexcel Allowed Memory Size of 134217728 Bytes Exhausted
Status Detail: 3045:The Currency Field Is Missing
Executing Git Commands via PHP
Table Name as Parameter Using Pdo/MySQL Prepared Statement
No Database Selected - PHP & MySQL
Is $_Server['Http_Referer'] Safe
Why Composer Can Not Find My Brand New Package on Packagist.Org
Reverse Order of String Like "Hello Word" Reverse as "Word Hello" in PHP
Confirmation That PHP Static Variables Do Not Persist Across Requests