I want count of total Friday available in each month. How to get that?
1.code
private static int getFridayCount(DayOfWeek dayOfWeek, LocalDate startDate) {
return //
}
I want count of total Friday available in each month. How to get that?
1.code
private static int getFridayCount(DayOfWeek dayOfWeek, LocalDate startDate) {
return //
}
Probably not the fastest, but I find this really simple to understand:
public static int numberOfDaysOfWeekInMonth(DayOfWeek dow, YearMonth yearMonth) {
LocalDate startOfMonth = yearMonth.atDay(1);
LocalDate first = startOfMonth.with(TemporalAdjusters.firstInMonth(dow));
LocalDate last = startOfMonth.with(TemporalAdjusters.lastInMonth(dow));
return (last.getDayOfMonth() - first.getDayOfMonth()) / 7 + 1;
}
Example usage:
System.out.println(
numberOfDaysOfWeekInMonth(
DayOfWeek.FRIDAY, YearMonth.of(2020, 9)
)
); // outputs 4
You may count every dayOfWeek
from startDate
to end of month like
import java.time.*;
public class Main {
public static void main(String[] args) {
DayOfWeek dow = DayOfWeek.FRIDAY;
LocalDate startDate = LocalDate.of(2020, 9 ,25);
System.out.println("Amount: " + getCountOfDayInMonth(dow, startDate));
}
private static int getCountOfDayInMonth(DayOfWeek dow, LocalDate startDate) {
LocalDate date = startDate;
int count = 0;
while (date.getMonth() == startDate.getMonth()) {
if (date.getDayOfWeek() == dow) {
count++;
}
date = date.plusDays(1);
}
return count;
}
}
Where date
is a LocalDate
beginning at startDate
and going through the current Month
.