【发布时间】:2016-12-02 14:14:34
【问题描述】:
我想改变瞬间:
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 转换为 ZonedDateTime,选择时区。然后在 ZonedDateTime 上设置时间。然后将 ZonedDateTime 转换为 Instant。
-
@WilliMentzel 我在真实代码中没有字符串。我在这里解析它只是为了重现最少的代码。日期时间算术的字符串操作看起来很笨拙。