加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:36:54 所属栏目:Java 来源:网络整理
导读:我想改变一个瞬间的时间: 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.56789
我想改变一个瞬间的时间:

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读