Java如何创建自定义的TemporalAdjuster?
在此示例中,我们将学习如何实现自定义TemporalAdjuster。我们将创建TemporalAdjuster一个从指定日期开始的下一个工作日。从星期一到星期五,我们将使用5个工作日。
定制的时间调节器类应该实现TemporalAdjuster接口,该接口定义了我们必须实现的单个adjustInto(Temporal)方法。
package org.nhooo.example.datetime;import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
public class NextWorkingDayAdjuster implements TemporalAdjuster {
@Override
public Temporal adjustInto(Temporal temporal) {
int field = temporal.get(ChronoField.DAY_OF_WEEK);
DayOfWeek dayOfWeek = DayOfWeek.of(field);
int daysToAdd = 1;
if (DayOfWeek.FRIDAY.equals(dayOfWeek)) {
daysToAdd = 3;
} else if (DayOfWeek.SATURDAY.equals(dayOfWeek)) {
daysToAdd = 2;
}
return temporal.plus(daysToAdd, ChronoUnit.DAYS);
}
}
该NextWorkingDayAdjuster移动暂时物件每天前进。除了在星期五或星期六,这将分别将时间对象向前移动三天或两天。这将使其在下一个工作日返回星期一。
创建自定义调整器之后,现在让我们创建一个使用NextWorkingDayAdjuster该类的示例。
package org.nhooo.example.datetime;import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjuster;
public class NextWorkingDayAdjusterDemo {
public static void main(String[] args) {
TemporalAdjuster nextWorkingDay = new NextWorkingDayAdjuster();
LocalDate now = LocalDate.now();
LocalDate nextDay = now.with(nextWorkingDay);
System.out.println("now = " + now);
System.out.println("nextWorkingDay = " + nextDay);
LocalDate friday = LocalDate.of(2016, Month.MARCH, 11);
nextDay = friday.with(nextWorkingDay);
System.out.println("friday = " + friday);
System.out.println("nextWorkingDay = " + nextDay);
LocalDate saturday = LocalDate.of(2016, Month.MARCH, 12);
nextDay = saturday.with(nextWorkingDay);
System.out.println("saturday = " + saturday);
System.out.println("nextWorkingDay = " + nextDay);
}
}
这是我们的代码的结果:
now = 2016-03-10nextWorkingDay = 2016-03-11
friday = 2016-03-11
nextWorkingDay = 2016-03-14
saturday = 2016-03-12
nextWorkingDay = 2016-03-14
以上是 Java如何创建自定义的TemporalAdjuster? 的全部内容, 来源链接: utcz.com/z/330725.html