0

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 // 
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • 1
    What's the purpose of the `dayOfWeek` and `startDate` parameters? Shouldn't the method have a `YearMonth` parameter instead? – Sweeper Sep 25 '20 at 07:00
  • If you are interested in Fridays only, why does the method have a `DayOfWeek` as parameter? – deHaar Sep 25 '20 at 07:01
  • Because of DayOfWeek we can pass any day like Monday Or Wednesdays etc startDate means each month of any date i have to pass – Techavidus User Sep 25 '20 at 07:14
  • 2
    See [Count days between two dates with Java 8 while ignoring certain days of week](https://stackoverflow.com/q/25798876/2711488)… – Holger Sep 25 '20 at 07:55

2 Answers2

4

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
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

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.

IQbrod
  • 2,060
  • 1
  • 6
  • 28
  • i can pass startDate means their is not startDate of any month its just date of each month which are any date – Techavidus User Sep 25 '20 at 07:16
  • Then why don't you directly pass a `Month` object ? If you want an answer for the whole month not regarding the startDate you pass, I suggest you to look at @Sweeper answer – IQbrod Sep 25 '20 at 07:18