java 如何将 Instant 转换为 LocalTime?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27340650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:39:17  来源:igfitidea点击:

How to convert a Instant to a LocalTime?

javadatetimejava-8

提问by Connorelsea

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

即使在阅读了大量教程之后,我也没有真正理解 Temporal Adjusters 或 Java 的新时间库。

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

我如何将 Instant 对象转换为 LocalTime 对象。我在想以下几点:

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?

但它不起作用。我该怎么做?

回答by Adam

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 是 UTC 风格的时间,区域不可知,总是 UTC。LocaleTime 是给定区域的时间。因此,鉴于 Instant 实现了 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.

但您收到“无法从 TemporalAccessor 获取 LocalTime”错误。相反,您需要说明“本地”在哪里。没有默认值 - 可能是一件好事。

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.

InstantStart.get(ChronoField.HOUR_OF_DAY) 抛出错误,因为它在概念上不支持它,您只能通过 LocalTime 实例访问 HOUR_OF_DAY 等。