将 LocalDateTime 转换为 Instant 需要 ZoneOffset.为什么?



我需要将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);

最新更新