[英]JDK8 adjust time of a java.time.Instant
I'm trying to adjust the time of a java.time.Instant
. 我正在尝试调整
java.time.Instant
的时间。
I tried this code: 我试过这段代码:
Instant validFrom = //from my method parameter
validFrom = validFrom.with(ChronoField.HOUR_OF_DAY, 19).with(ChronoField.MINUTE_OF_DAY, 00)
.with(ChronoField.SECOND_OF_DAY, 00).with(ChronoField.MILLI_OF_DAY, 00);
But I've an exception: 但我有一个例外:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
at java.time.Instant.with(Instant.java:720)
This is quite expected reading the documentation and checking the source code. 这是非常期待阅读文档和检查源代码。 It's not really clear to me why I can't do that.
我不清楚为什么我不能这样做。 Is there another way to to this operation without incurring in many conversions?
是否有另一种方法可以在不进行多次转换的情况下进行此操作?
This is because Instant
has no timezone information. 这是因为
Instant
没有时区信息。 19:00 hours doesn't represent anything useful, unless you attach a timezone to it. 19:00小时不代表任何有用的东西,除非你附上一个时区。
You can convert it to a ZonedDateTime
object, and then convert it back to an Instant
like this: 您可以将其转换为
ZonedDateTime
对象,然后将其转换回Instant
如下所示:
public void testInstant(){
Instant now = Instant.now();
ZonedDateTime utc = now.atZone(ZoneId.of("UTC"));
ZonedDateTime zonedDateTime = utc.withHour(19)
.withMinute(0)
.withSecond(0);
Instant instant = zonedDateTime.toInstant();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.