gpt4 book ai didi

java - 使用 java.time 替换时刻中的时间部分

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:23 24 4
gpt4 key购买 nike

我想改变一个瞬间的时间:

Instant instant = Instant.parse("2016-03-23T17:14:00.092812Z");
LocalTime newTime = LocalTime.parse("12:34:45.567891");
instant.with(newTime);

我希望得到同一日期的瞬间,但时间是新的,即 2016-03-23 12:34:45.567891。

但它抛出异常:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: NanoOfDay
at java.time.Instant.with(Instant.java:720)
at java.time.Instant.with(Instant.java:207)
at java.time.LocalTime.adjustInto(LocalTime.java:1333)
at java.time.Instant.with(Instant.java:656)

有什么解决办法吗?

最佳答案

Instant 没有本地日历日期或本地时间的概念。它的方法 toString() 根据日期和时间描述 UTC 时间轴上的时刻在偏移量 UTC+00:00,但它仍然是一个时刻,而不是具有本地上下文的信息。

但是,您可以使用以下转换。转换为本地时间戳,操作本地时间戳,然后转换回即时/瞬间。 重要的是要看到转换取决于具体时区。

Instant instant = Instant.parse("2016-03-23T17:14:00.092812Z");
LocalTime newTime = LocalTime.parse("12:34:45.567891");

// or choose another one, the conversion is zone-dependent!!!
ZoneId tzid = ZoneId.systemDefault();
Instant newInstant =
instant.atZone(tzid).toLocalDate().atTime(newTime).atZone(tzid).toInstant();
System.out.println(newInstant); // 2016-03-23T11:34:45.567891Z (in my zone Europe/Berlin)

关于java - 使用 java.time 替换时刻中的时间部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40934230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com