Java examples for Date Time:Date Time Adjust
Creating a Custom Date Adjuster
import static java.time.DayOfWeek.FRIDAY; import static java.time.DayOfWeek.MONDAY; import static java.time.DayOfWeek.SATURDAY; import static java.time.DayOfWeek.SUNDAY; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalTime; import java.time.Month; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAdjusters; public class Main { public static void main(String[] args) { LocalDate ld1 = LocalDate.of(2013, Month.DECEMBER, 12); // Thursday LocalDate ld2 = LocalDate.of(2013, Month.DECEMBER, 13); // Friday LocalDate ld3 = LocalDate.of(2013, Month.DECEMBER, 14); // Saturday LocalDate ld1Adjusted = ld1.with(WEEKDAYS_WITH_NO_FRIDAY_13); System.out.println(ld1 + " adjusted to " + ld1Adjusted); LocalDate ld2Adjusted = ld2.with(WEEKDAYS_WITH_NO_FRIDAY_13); System.out.println(ld2 + " adjusted to " + ld2Adjusted); LocalDate ld3Adjusted = ld3.with(WEEKDAYS_WITH_NO_FRIDAY_13); System.out.println(ld3 + " adjusted to " + ld3Adjusted); // Use it to adjust a ZonedDateTime ZonedDateTime zdt = ZonedDateTime.of(ld2, LocalTime.of(8, 45), ZoneId.of("America/Chicago")); ZonedDateTime zdtAdjusted = zdt.with(WEEKDAYS_WITH_NO_FRIDAY_13); System.out.println(zdt + " adjusted to " + zdtAdjusted); }/*from ww w. ja va 2s .c o m*/ static TemporalAdjuster WEEKDAYS_WITH_NO_FRIDAY_13 = TemporalAdjusters .ofDateAdjuster(Main::getWeekDayNoFriday13); private static LocalDate getWeekDayNoFriday13(LocalDate date) { // Initialize the new date with the original one LocalDate newDate = date; DayOfWeek day = date.getDayOfWeek(); if (day == SATURDAY || day == SUNDAY || (day == FRIDAY && date.getDayOfMonth() == 13)) { // Return next Monday newDate = date.with(TemporalAdjusters.next(MONDAY)); } return newDate; } }