Skipping Weekends While Adding Days to LocalDate in Java 8

1. Overview

In this tutorial, we will briefly look at the algorithm to skip weekends while adding days to a LocalDate instance in Java 8.

We’ll also go through the algorithm to subtract days from LocalDate object whilst skipping weekends.

2. Adding Days

In this method, we keep on adding one day to the LocalDate object until we have added the required numbers of days. While adding a day, we check whether the day of the new LocalDate instance is a Saturday or a Sunday.

If the check returns true, then we don’t increment the counter for the number of days added until that point. However, if the current day is a weekday, then we increment the counter.

In this way, we keep on adding days until the counter is equal to the number of days that are supposed to be added:

public static LocalDate addDaysSkippingWeekends(LocalDate date, int days) {
    LocalDate result = date;
    int addedDays = 0;
    while (addedDays < days) {
        result = result.plusDays(1);
        if (!(result.getDayOfWeek() == DayOfWeek.SATURDAY || result.getDayOfWeek() == DayOfWeek.SUNDAY)) {
            ++addedDays;
        }
    }
    return result;
}

In the above code, we use the plusDays() method of LocalDate object to add days to the result object. We increment the addedDays variable only when the day is a weekday. When the variable addedDays is equal to days variable, we stop adding a day to result LocalDate object.

3. Subtracting Days

Similarly, we can subtract days from LocalDate object using the minusDays() method until we have subtracted the required number of days.

To achieve this, we’ll keep a counter for the number of days subtracted that is incremented only when the resulted day is a weekday:

public static LocalDate subtractDaysSkippingWeekends(LocalDate date, int days) {
    LocalDate result = date;
    int subtractedDays = 0;
    while (subtractedDays < days) {
        result = result.minusDays(1);
        if (!(result.getDayOfWeek() == DayOfWeek.SATURDAY || result.getDayOfWeek() == DayOfWeek.SUNDAY)) {
            ++subtractedDays;
        }
    }
    return result;
}

From the above implementation, we can see that subtractedDays is only incremented when the result LocalDate object is a weekday. Using the while loop, we subtract days until subtractedDays is equal to the days variable.

4. Conclusion

In this brief article, we looked at algorithms for adding days to and subtracting days from LocalDate object skipping weekends. Furthermore, we looked at their implementations in Java.

As always, the full source code of the working examples is available over on GitHub.