我想改变一个瞬间的时间:
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-8,time
来源: https://codeday.me/bug/20190727/1553342.html