java.time.LocalDate adjustInto()方法使用说明

方法签名:

public Temporal adjustInto(Temporal temporal)

方法说明:将参数的日期,调整为和当前对象一致

代码示例:

import java.time.LocalDate;
import java.time.temporal.Temporal;

/**
 *  adjustInto()
 */
public class LocalDate_adjustInto {
    public static void main(String[] args) {
        LocalDate ld = LocalDate.parse("2021-02-03");
        System.out.println("ld:     "+ld);
        LocalDate now = LocalDate.now();
        System.out.println("now:    "+now);
        //now调整和ld一致
        Temporal temporal = ld.adjustInto(now);
        System.out.println(temporal);
        //ld调整和now一致
        Temporal temporal1 = now.adjustInto(ld);
        System.out.println(temporal1);

    }
}

输出:

ld:     2021-02-03
now:    2021-06-03
2021-02-03
2021-06-03

因为Java8的time包下的日期类基本都是不可变的,这里的调整也不是改这个参数对应的值,这是生成了一个新的日期对象。

我们查看源码:

@Override
default Temporal adjustInto(Temporal temporal) {
     return temporal.with(EPOCH_DAY, toEpochDay());
}

这里是调用的with()方法,with方法的作用就是将一个对象的日期时间调整为一个给定的目标值。

这里的with方法最终调用的是LocalDate中的with重写方法:

@Override
public LocalDate with(TemporalField field, long newValue) {
	if (field instanceof ChronoField) {
		ChronoField f = (ChronoField) field;
		f.checkValidValue(newValue);
		switch (f) {
			case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek().getValue());
			case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
			case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
			case DAY_OF_MONTH: return withDayOfMonth((int) newValue);
			case DAY_OF_YEAR: return withDayOfYear((int) newValue);
			case EPOCH_DAY: return LocalDate.ofEpochDay(newValue);
			case ALIGNED_WEEK_OF_MONTH: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_MONTH));
			case ALIGNED_WEEK_OF_YEAR: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_YEAR));
			case MONTH_OF_YEAR: return withMonth((int) newValue);
			case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth());
			case YEAR_OF_ERA: return withYear((int) (year >= 1 ? newValue : 1 - newValue));
			case YEAR: return withYear((int) newValue);
			case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year));
		}
		throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
	}
	return field.adjustInto(this, newValue);
}