我需要将一个 LocalDateTime
对象转换成一个新的 Instant
对象。
我发现 LocalDateTime
有一个 toInstant
方法,但它需要一个 ZoneOffset
参数。
我不太清楚如何使用它,或者 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.atZone(ZoneId.systemDefault()).toInstant()
。 - Cassio Luis Felippe你可以尝试这个:
LocalDateTime dateTime = LocalDateTime.of(2018, Month.OCTOBER, 10, 31, 56);
Instant instant = dateTime.atZone(ZoneId.of("Europe/Rome")).toInstant();
System.out.println(instant);