Java - Create Date adjuster to return only weekdays, except Friday 13.

Introduction

The adjuster has been defined as a constant in the class.

Using the adjuster is to pass the WEEKDAYS_WITH_NO_FRIDAY_13 constant to the with() method of the datetime classes that can supply a LocalDate.

LocalDate ld = LocalDate.of(2013, Month.DECEMBER, 13); // Friday
LocalDate ldAdjusted = ld.with(WEEKDAYS_WITH_NO_FRIDAY_13); // Next Monday

Demo

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  www.ja v  a2 s . c om*/

  public final 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;
  }
}

Result

Related Topic