Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Instant to a LocalTime?

I don't really understand TemporalAdjusters or Java's new time library even after reading numerous tutorials.

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

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

But it isn't working. How can I do this?

like image 606
Connorelsea Avatar asked Dec 07 '14 07:12

Connorelsea


People also ask

How do you convert instant to timezone?

Conversion Now we will call the atZone() method on the instant object to convert it to a ZonedDateTime object. ZonedDateTime zonedDateTime = instant. atZone(ZoneId. of( "Asia/Kolkata" ));

Is Instant NOW () UTC?

Java8 Instant. now() gives the current time already formatted in UTC.

What does LocalTime represent time without date?

What does LocalTime represent? Explanation: LocalTime of joda library represents time without date. 9.


1 Answers

The way I understand it... Instant is a UTC style time, agnostic of zone always UTC. LocalTime is a time independent of given zone. So you'd expect the following would work given that Instant implements TemporalAccessor,

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

but you get "Unable to obtain LocalTime from TemporalAccessor" error. Instead you need to state where "local" is. There is no default - probably 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));

Output

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

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

like image 170
Adam Avatar answered Sep 27 '22 18:09

Adam