How to convert Instant to LocalTime?

I am not very good at Temporal Adjusters or the new Java library even after reading numerous tutorials.

How to convert an Instant object to a LocalTime object. I was thinking of something like the following:

LocalTime time = LocalTime.of( instantStart.get(ChronoField.HOUR_OF_DAY), instantStart.get(ChronoField.MINUTE_OF_HOUR) ); 

But it does not work. How can I do it?

+7
java datetime java-8
source share
1 answer

The way I understand it ... Instant in UTC style, zone agnostic is always UTC. LocaleTime is the time in this zone. So you expect the following to work, given that Instant implements TemporalAccessor,

 Instant instant = Instant.now(); LocalTime local = LocalTime.from(instant); 

but you will get the error "Failed to get LocalTime from TemporalAccessor". Instead, you need to specify where "local" is. No default - perhaps a good thing.

 Instant instant = Instant.now(); LocalTime local = LocalTime.from(instant.atZone(ZoneId.of("GMT+3"))); System.out.println(String.format("%s => %s", instant, local)); 

Exit

 2014-12-07T07:52:43.900Z => 10:52:43.900 

instantStart.get (ChronoField.HOUR_OF_DAY) throws an error, because it does not support it conceptually, you can only access HOUR_OF_DAY, etc. through an instance of LocalTime.

+11
source share

All Articles