我需要将LocalDateTime
对象转换为新的Instant
对象。
我意识到LocalDateTime
有一个toInstant
的方法,但它要求我ZoneOffset
.
我不太清楚如何使用它,或者ZoneOffset
意味着什么。
不能将LocalDateTime
直接转换为Instant
,因为LocalDateTime
可以表示许多时刻。它不代表某个特定的时刻。
这是一个LocalDateTime
:
23/10/2018 09:30:00
你能通过看一眼就弄清楚上面到底指的是哪个时刻吗?不。因为在英国的那个时间与中国的那个时间是不同的。
要弄清楚该时间指的是哪个时刻,您还需要知道它与 UTC 偏移了多少小时,这就是ZoneOffset
基本上所代表的。
例如,对于 8 小时的偏移量,您可以这样写:
localDateTime.toInstant(ZoneOffset.ofHours(8))
或者,如果您知道始终希望该本地日期时间的区域偏移量位于当前时区,则可以将ZoneOffset.ofHours(8)
替换为:
ZoneId.systemDefault().getRules().getOffset(localDateTime)
在将其转换为瞬间之前,您应该考虑要使用的偏移量。
你可以试试这个:
LocalDateTime dateTime = LocalDateTime.of(2018, Month.OCTOBER, 10, 31, 56);
Instant instant = dateTime.atZone(ZoneId.of("Europe/Rome")).toInstant();
System.out.println(instant);