package com.logicbig.example.instant;
import java.time.Instant;
import java.time.temporal.ChronoField;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
public class WithExample {
public static void main(String... args) {
Instant i = Instant.now();
System.out.println(i);
Instant i2 = i.with(sameInstantOfLastDay);
System.out.println(i2);
}
private static final TemporalAdjuster sameInstantOfLastDay = new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal temporal) {
if (temporal.isSupported(ChronoField.INSTANT_SECONDS)) {
long i = temporal.getLong(ChronoField.INSTANT_SECONDS);
return Instant.ofEpochSecond(i - (60 * 60 * 24));
}
return null;
}
};
}
Output
2017-05-01T20:56:57.567Z
2017-04-30T20:56:57Z
package com.logicbig.example.instant;
import java.time.Instant;
import java.time.temporal.ChronoField;
import java.time.temporal.UnsupportedTemporalTypeException;
public class WithExample2 {
public static void main(String... args) {
Instant i = Instant.now();
System.out.println(i);
for (ChronoField chronoField : ChronoField.values()) {
with(i, chronoField);
}
}
private static void with(Instant d, ChronoField chronoField) {
try {
Instant d2 = d.with(chronoField, 1);
System.out.printf("%15s => %s%n", chronoField.name(), d2);
} catch (UnsupportedTemporalTypeException e) {
System.out.printf("--%s not supported.%n", chronoField);
}
}
}
Output
2017-05-01T20:56:59.599Z
NANO_OF_SECOND => 2017-05-01T20:56:59.000000001Z
--NanoOfDay not supported.
MICRO_OF_SECOND => 2017-05-01T20:56:59.000001Z
--MicroOfDay not supported.
MILLI_OF_SECOND => 2017-05-01T20:56:59.001Z
--MilliOfDay not supported.
--SecondOfMinute not supported.
--SecondOfDay not supported.
--MinuteOfHour not supported.
--MinuteOfDay not supported.
--HourOfAmPm not supported.
--ClockHourOfAmPm not supported.
--HourOfDay not supported.
--ClockHourOfDay not supported.
--AmPmOfDay not supported.
--DayOfWeek not supported.
--AlignedDayOfWeekInMonth not supported.
--AlignedDayOfWeekInYear not supported.
--DayOfMonth not supported.
--DayOfYear not supported.
--EpochDay not supported.
--AlignedWeekOfMonth not supported.
--AlignedWeekOfYear not supported.
--MonthOfYear not supported.
--ProlepticMonth not supported.
--YearOfEra not supported.
--Year not supported.
--Era not supported.
INSTANT_SECONDS => 1970-01-01T00:00:01.599Z
--OffsetSeconds not supported.