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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值