How To Add Working Days To A Date In Java
Chapter:
Date and Time
Last Updated:
22-06-2023 14:15:14 UTC
Program:
/* ............... START ............... */
import java.time.DayOfWeek;
import java.time.LocalDate;
public class WorkingDaysCalculator {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2023, 6, 22); // Starting date
int workingDaysToAdd = 5; // Number of working days to add
LocalDate resultDate = addWorkingDays(startDate, workingDaysToAdd);
System.out.println("Result: " + resultDate);
}
public static LocalDate addWorkingDays(LocalDate startDate, int workingDays) {
int count = 0;
while (workingDays > 0) {
startDate = startDate.plusDays(1);
if (isWorkingDay(startDate)) {
workingDays--;
}
count++;
}
System.out.println("Loop iterations: " + count);
return startDate;
}
public static boolean isWorkingDay(LocalDate date) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
return dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY;
}
}
/* ............... END ............... */
Output
Result: 2023-06-29
Loop iterations: 7
In this example, it adds 5 working days to the starting date of June 22, 2023, resulting in
the output date of June 29, 2023. The loop iterations indicate that it took 7 iterations to find the 5
working days, considering weekends as non-working days.
Notes:
-
In the above example, we have a method addWorkingDays that takes a LocalDate object as the starting date and an integer representing the number of working days to add. It iterates over each day, checks if it is a working day using the isWorkingDay method, and decrements the working days count until it reaches 0.
- The isWorkingDay method checks if the given date is not a Saturday or Sunday, assuming these are non-working days.
- The result is the LocalDate object after adding the specified number of working days.
- Please note that this example assumes a simple scenario where weekends (Saturday and Sunday) are considered non-working days. If you have additional holidays or other non-working days to consider, you would need to modify the isWorkingDay method accordingly.