user2781389 user2781389 - 1 year ago 93
Java Question

last working day of previous month with LocalDate

public static String getLastWorkingDayOfPreviousMonth() {

LocalDate lastDayOfCurrentMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
LocalDate lastWorkingDayOfMonth;

switch (DayOfWeek.of(lastDayOfCurrentMonth.get(ChronoField.DAY_OF_WEEK))) {
case SATURDAY:
lastWorkingDayOfMonth = lastDayOfCurrentMonth.minusMonths(1);
break;
case SUNDAY:
lastWorkingDayOfMonth = lastDayOfCurrentMonth.minusMonths(2);
break;
default:
lastWorkingDayOfMonth = lastDayOfCurrentMonth;
}

return getFormattedDate(lastWorkingDayOfMonth);
}


The above gives last working day of the current month. How can I get the last working day of the
Previous
month adjusting the above?

VGR VGR
Answer Source

Sometimes, the simple approach is better than a clever approach:

LocalDate lastWorkingDayOfMonth = LocalDate.now().withDayOfMonth(1);
do {
    lastWorkingDayOfMonth = lastWorkingDayOfMonth.minusDays(1);
} while (lastWorkingDayOfMonth.getDayOfWeek() == DayOfWeek.SATURDAY ||
         lastWorkingDayOfMonth.getDayOfWeek() == DayOfWeek.SUNDAY);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download