java 39 lines · 7 steps

Counting business days between two dates in Java

A static utility counts weekdays between two dates, subtracting weekday holidays, using a whole-week shortcut for speed.

Explained by highlit
1public final class BusinessDays {
2 
3 private BusinessDays() {
4 }
5 
6 public static long between(LocalDate start, LocalDate end, Set<LocalDate> holidays) {
7 if (start.isAfter(end)) {
8 return -between(end, start, holidays);
9 }
10 
11 long totalDays = ChronoUnit.DAYS.between(start, end);
12 long fullWeeks = totalDays / 7;
13 long businessDays = fullWeeks * 5;
14 
15 LocalDate cursor = start.plusDays(fullWeeks * 7);
16 while (cursor.isBefore(end)) {
17 if (!isWeekend(cursor)) {
18 businessDays++;
19 }
20 cursor = cursor.plusDays(1);
21 }
22 
23 long holidayCount = holidays.stream()
24 .filter(h -> !h.isBefore(start) && h.isBefore(end))
25 .filter(h -> !isWeekend(h))
26 .count();
27 
28 return businessDays - holidayCount;
29 }
30 
31 public static long between(LocalDate start, LocalDate end) {
32 return between(start, end, Collections.emptySet());
33 }
34 
35 private static boolean isWeekend(LocalDate date) {
36 DayOfWeek day = date.getDayOfWeek();
37 return day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY;
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Decomposing a range into full weeks plus a remainder avoids iterating every single day.
  2. 2Handling the reversed-argument case by recursing with a negated result keeps the core logic one-directional.
  3. 3A private constructor signals a class meant only for static helper methods.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Counting business days between two dates in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code