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

方法签名:

Temporal	adjustInto(Temporal temporal)

方法说明:调整指定时间,与当前对象的时间保持一致。

代码示例:

public class LocalTime_adjustInto {

    public static void main(String[] args) {
        LocalTime lt = LocalTime.parse("13:15:23");
        System.out.println("lt:     "+lt);
        LocalTime now = LocalTime.now();
        System.out.println("now:    "+now);
        //now调整和lt一致
        Temporal temporal = lt.adjustInto(now);
        System.out.println(temporal);
        //lt调整和now一致
        Temporal temporal1 = now.adjustInto(lt);
        System.out.println(temporal1);

    }
}

输出:

lt:     13:15:23
now:    09:21:50.178
13:15:23
09:21:50.178

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

源码逻辑与LocalDate的源码逻辑是一致的,时间修改通过with方法。

@Override
public Temporal adjustInto(Temporal temporal) {
    return temporal.with(NANO_OF_DAY, toNanoOfDay());
}
@Override
public LocalTime with(TemporalField field, long newValue) {
	if (field instanceof ChronoField) {
		ChronoField f = (ChronoField) field;
		f.checkValidValue(newValue);
		switch (f) {
			case NANO_OF_SECOND: return withNano((int) newValue);
			case NANO_OF_DAY: return LocalTime.ofNanoOfDay(newValue);
			case MICRO_OF_SECOND: return withNano((int) newValue * 1000);
			case MICRO_OF_DAY: return LocalTime.ofNanoOfDay(newValue * 1000);
			case MILLI_OF_SECOND: return withNano((int) newValue * 1000_000);
			case MILLI_OF_DAY: return LocalTime.ofNanoOfDay(newValue * 1000_000);
			case SECOND_OF_MINUTE: return withSecond((int) newValue);
			case SECOND_OF_DAY: return plusSeconds(newValue - toSecondOfDay());
			case MINUTE_OF_HOUR: return withMinute((int) newValue);
			case MINUTE_OF_DAY: return plusMinutes(newValue - (hour * 60 + minute));
			case HOUR_OF_AMPM: return plusHours(newValue - (hour % 12));
			case CLOCK_HOUR_OF_AMPM: return plusHours((newValue == 12 ? 0 : newValue) - (hour % 12));
			case HOUR_OF_DAY: return withHour((int) newValue);
			case CLOCK_HOUR_OF_DAY: return withHour((int) (newValue == 24 ? 0 : newValue));
			case AMPM_OF_DAY: return plusHours((newValue - (hour / 12)) * 12);
		}
		throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
	}
	return field.adjustInto(this, newValue);
}