How to convert a Instant to a LocalTime?

倖福魔咒の 提交于 2019-12-23 06:59:02

问题


I'm not really understanding Temporal Adjusters or Java's new time library even after reading numerous tutorials.

How would 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 would I do this?


回答1:


The way I understand it... Instant is a UTC style time, agnostic of zone always UTC. LocaleTime is time at a 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.



来源:https://stackoverflow.com/questions/27340650/how-to-convert-a-instant-to-a-localtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!