我们除了使用每个日期类自己实现的调节器方法,使用工具类TemporalAdjusters中定义的方法外,还可以自定义调节器。
例如:公司是每月15号发薪,如果15号遇到周六或周日,那么就顺延到下周一,此时我要实现一个调节器,返回实际发薪日期。
其实就是实现一个薪水发放日期查询的功能。
代码;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
/**
* @Auther: www.itzhimei.com
* @Description: 自定义时间调节器
*/
public class MyselfTemporalAdjuster implements TemporalAdjuster {
/**
* 当前日期如果是15号,则是发薪日,但是如果是周六或周日,则顺延到下周一
* @param temporal
* @return
*/
@Override
public Temporal adjustInto(Temporal temporal) {
LocalDate localDate = LocalDate.from(temporal);
LocalDate payLocalDate = localDate.withDayOfMonth(15);
if(payLocalDate.getDayOfWeek() == DayOfWeek.SATURDAY || payLocalDate.getDayOfWeek() == DayOfWeek.SUNDAY) {
return localDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
}
return payLocalDate;
}
public static void main(String[] args) {
LocalDate localDate = LocalDate.of(2021,6,16);
System.out.println("当前日期:"+localDate+",今天是:"+localDate.getDayOfWeek());
MyselfTemporalAdjuster myta = new MyselfTemporalAdjuster();
LocalDate temporal = (LocalDate)myta.adjustInto(localDate);
System.out.println("发薪日期:"+temporal+",发薪日是:"+temporal.getDayOfWeek());
}
}
输出:
当前日期:2021-06-16,今天是:WEDNESDAY
发薪日期:2021-06-15,发薪日是:TUESDAY