I have two java.time.Instant objects
Instant dt1;
Instant dt2;
I want to get time (only hours and minutes without date) from dt2 and set it to dt1. What is the best way to to this? Using
dt2.get(ChronoField.HOUR_OF_DAY)
throws java.time.temporal.UnsupportedTemporalTypeException
解决方案
You have to interpret the Instant at some time zone to get ZonedDateTime. As an Instant measures the ellapsed seconds and nano seconds from epoch 1970-01-01T00:00:00Z you should use UTC to get the same time as the Instant would print. (Z ≙ Zulu Time ≙ UTC)
Getting the time
Instant instant;
// get overall time
LocalTime time = instant.atZone(ZoneOffset.UTC).toLocalTime();
// get hour
int hour = instant.atZone(ZoneOffset.UTC).getHour();
// get minute
int minute = instant.atZone(ZoneOffset.UTC).getMinute();
// get second
int second = instant.atZone(ZoneOffset.UTC).getSecond();
// get nano
int nano = instant.atZone(ZoneOffset.UTC).getNano();
There are also methods to get days, month and year (getX).
Setting the time
Instants are immutable so you can only "set" the time by creating a copy of your instant with the given time change.
instant = instant.atZone(ZoneOffset.UTC)
.withHour(hour)
.withMinute(minute)
.withSecond(second)
.withNano(nano)
.toInstant();
There are also methods to alter days, month and year (withX) as well as methods to add (plusX) or subtract (minusX) time or date values.