Java Reference
In-Depth Information
Today: 2014-01-08
Next Monday: 2014-01-13
Last day of month: 2014-01-31
Date after adding 3 months and 2 days: 2014-04-10
Let's create a custom date adjuster. If the date being adjusted is on weekends or Friday 13, it returns the next
Monday. Otherwise, it returns the original date. That is, the adjuster will return only weekdays, except Friday 13.
Listing 12-16 contains the complete code for the adjuster. The adjuster has been defined as a constant in the class.
Using the adjuster is as easy as passing the CustomAdjusters.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(CustomAdjusters.WEEKDAYS_WITH_NO_FRIDAY_13); // Next Monday
Listing 12-16. Creating a Custom Date Adjuster
// CustomAdjusters.java
package com.jdojo.datetime;
import java.time.DayOfWeek;
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.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class CustomAdjusters {
public final static TemporalAdjuster WEEKDAYS_WITH_NO_FRIDAY_13 =
TemporalAdjusters.ofDateAdjuster(CustomAdjusters::getWeekDayNoFriday13);
// No public constructor as it is a utility class
private CustomAdjusters() { }
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;
}
}
 
Search WWH ::




Custom Search