diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/AddSubtractDaysSkippingWeekendsUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/AddSubtractDaysSkippingWeekendsUtils.java new file mode 100644 index 0000000000..bf32fdb79a --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/AddSubtractDaysSkippingWeekendsUtils.java @@ -0,0 +1,31 @@ +package com.baeldung.datetime; + +import java.time.DayOfWeek; +import java.time.LocalDate; + +public class AddSubtractDaysSkippingWeekendsUtils { + + 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; + } + + 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; + } +} diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java new file mode 100644 index 0000000000..d60a0f4015 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/AddSubtractDaysSkippingWeekendsUtilsUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import java.time.LocalDate; + +public class AddSubtractDaysSkippingWeekendsUtilsUnitTest { + + @Test + public void givenLocalDateAndDaysToAdd_thenAddDaysSkippingWeekends() { + LocalDate initialDate = LocalDate.of(2019, 11, 7); + LocalDate expectedDate = LocalDate.of(2019, 11, 13); + LocalDate result = AddSubtractDaysSkippingWeekendsUtils.addDaysSkippingWeekends(initialDate, 4); + assertEquals(expectedDate, result); + } + + @Test + public void givenLocalDateAndDaysToSubtract_thenSubtractDaysSkippingWeekends() { + LocalDate initialDate = LocalDate.of(2019, 11, 7); + LocalDate expectedDate = LocalDate.of(2019, 11, 1); + LocalDate result = AddSubtractDaysSkippingWeekendsUtils.subtractDaysSkippingWeekends(initialDate, 4); + assertEquals(expectedDate, result); + } + +}