问题描述
即使阅读了许多教程,我还是不太了解TemporalAdjusters或Java的新时间库.
I don't really understand TemporalAdjusters or Java's new time library even after reading numerous tutorials.
如何将 Instant
对象转换为 LocalTime
对象.我正在按照以下思路进行思考:
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?
推荐答案
我的理解方式... Instant是UTC风格的时间,与区域始终UTC无关.LocalTime是与给定区域无关的时间.因此,如果 Instant
实现了 TemporalAccessor
,
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);
,但是您收到无法从TemporalAccessor获取LocalTime"错误.相反,您需要说明本地"的位置.是.没有默认值-可能是一件好事.
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));
输出
2014-12-07T07:52:43.900Z => 10:52:43.900
instantStart.get(ChronoField.HOUR_OF_DAY)
抛出错误,因为它在概念上不支持它,您只能通过LocalTime实例访问HOUR_OF_DAY等.
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.
这篇关于如何将Instant转换为LocalTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!