Date Time API added from Java 8. In the code written using LocalDateTime in this, I sometimes see such code.
Set each field one by one.java
LocalDateTime ldt = LocalDateTime.now().withHour(12).withMinute(0).withSecond(0).withNano(0);
The setting is like "Today's 12 o'clock", but each field of time is set one by one.
Well, when I used Calendar, it was basically one by one, so it may have happened in the flow.
However, this is inefficient because a new instance is created each time withXxx ()
.
LocalDateTime # with is used in such cases. That's right.
public LocalDateTime with(TemporalAdjuster adjuster) Returns an adjusted copy of this date / time. It adjusts the date / time and returns a LocalDateTime based on this date / time. Adjustments are made using the specified adjuster strategy object. Please refer to the adjuster documentation to understand what adjustments will be made.
I'm not very familiar with TemporalAdjuster, but here I will simply introduce the following usage.
Set at 12 o'clock in one shot.java
LocalDateTime ldt = LocalDateTime.now().with(LocalTime.of(12, 0));
LocalTime also implements this TemporalAdjuster, so you can pass it to the with method. And it changes the time of the instance of LocalDateTime to the time of the argument.
Recommended Posts