Here is one possibility, there may be others that are more concise.
Using the following dates as starting and ending points.
LocalDate start = LocalDate.of(2020, 1, 1);
LocalDate end = LocalDate.of(2020,4,18);
Now define a Predicate
to ignore Saturdays and Sundays. This will be applied to the date stream generated below.
Predicate<LocalDate> onlyWeekDays = ld -> !ld.getDayOfWeek()
.equals(DayOfWeek.SATURDAY)
&& !ld.getDayOfWeek().equals(DayOfWeek.SUNDAY);
Now use the datesUntil
method to generate a stream of dates between the starting and end points.
- The end date is increased by 1 day to make the stream inclusive of the ending date.
- The aforementioned filter is applied to screen out weekends.
- And the remaining dates are simply counted.
long days = start.datesUntil(end.plusDays(1)).filter(onlyWeekDays::test).count();
System.out.println(days);
All date related methods used are from the java.time package in the Java API.
Note: As an alternative as mentioned in the comments, an EnumSet
of the DayofWeek
enum would also serve as a filter. It would be used as follows:
Set<DayOfWeek> wkends =
EnumSet.of( DayOfWeek.SATURDAY,DayOfWeek.SUNDAY );
long days =
start
.datesUntil( end.plusDays(1) )
.filter( ld -> !wkends.contains( ld.getDayOfWeek() ) )
.count()
;