Learn to count the number of business days between two given dates in Java 8. The given example takes the holiday list as an optional list and uses predicates to check weekends or holidays.
Calculate number of business days
In this example, for simplicity sake, we have created two predicates to check if day is a weekend or is a holiday.
To get business days count, we first get the total days difference between two dates using ChronoUnit.DAYS.between() method.
Then we get a stream of dates from start date to end date and check each date against out two predicates.
If the day is no weekend or holiday, we consider it business day and get all count using stream aggregation method count()
.
import java.time.DayOfWeek; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; public class BusinessDaysExamples { public static void main(String[] args) { LocalDate today = LocalDate.of(2020, 5, 5); // Add one holiday for testing List<LocalDate> holidays = new ArrayList<>(); holidays.add(LocalDate.of(2020, 5, 11)); holidays.add(LocalDate.of(2020, 5, 1)); System.out.println(countBusinessDaysBetween(today, today.plusDays(20), Optional.empty())); System.out.println(countBusinessDaysBetween(today, today.plusDays(20), Optional.of(holidays))); } private static long countBusinessDaysBetween(LocalDate startDate, LocalDate endDate, Optional<List<LocalDate>> holidays) { if (startDate == null || endDate == null || holidays == null) { throw new IllegalArgumentException("Invalid method argument(s) to countBusinessDaysBetween(" + startDate + "," + endDate + "," + holidays + ")"); } Predicate<LocalDate> isHoliday = date -> holidays.isPresent() ? holidays.get().contains(date) : false; Predicate<LocalDate> isWeekend = date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY; long daysBetween = ChronoUnit.DAYS.between(startDate, endDate); long businessDays = Stream.iterate(startDate, date -> date.plusDays(1)).limit(daysBetween) .filter(isHoliday.or(isWeekend).negate()).count(); return businessDays; } }
Program output.
14 13
Drop me your questions related to Calculate the number of weekdays between two dates in Java.
Happy Learning !!