pri05
pri05

Reputation: 99

Find if the current date is the first day of the month in JAVA excluding weekends and holiday

I have a problem to find if the current date is the first day of the month, if so I have do some logic. First day of the month should exclude weekends and holidays. Holidays are pulled in a list from the database for the current year

Function should accept today's date as input and give boolean if the current day is first day of the month excluding weekends and holiday.

I tried with this logic:

boolean firstBusinessDayOfMonth(YearMonth month) {

 
    final Set<DayOfWeek> businessDays = EnumSet.of(
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
    );

    return
        month.atDay(1).datesUntil(month.plusMonths(1).atDay(1))
            .filter(date -> businessDays.contains(date.getDayOfWeek()))
            .filter(date -> !isHoliday(date))
            .findFirst();
         //return should compare with current date and give true or false
}

Some examples:

For June, 2024

June1 (Saturday) => false

June2 (Sunday) => false

June3 (Monday and !Holiday) => true

June4 (Tuesday and !Holiday but not first of the month) => false

Upvotes: -2

Views: 132

Answers (1)

DuncG
DuncG

Reputation: 15196

Given that you need to determine which day is first of any given month, change the return value of firstBusinessDayOfMonth from boolean to LocalDate and return the first matching date from the datesUntil() stream.

/**
 * @return First business day of the month or null if unknown
 */
LocalDate firstBusinessDayOfMonth(YearMonth month) {

    EnumSet<DayOfWeek> businessDays = EnumSet.complementOf(EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY));

    return month.atDay(1).datesUntil(month.plusMonths(1).atDay(1))
            .filter(date -> businessDays.contains(date.getDayOfWeek()))
            .filter(date -> !isHoliday(date) )
            .findFirst().orElse(null);
}

Then there is a simple check to determine if current day is first of the month:

public static boolean isFirstDayOfMonth(LocalDate when) {
    return when.equals(firstBusinessDayOfMonth(YearMonth.from(when)));
}

Example:

boolean isFirst = isFirstDayOfMonth(LocalDate.now());

Upvotes: 2

Related Questions