Java 如何将 LocalDate 转换为 Instant?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23215299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a LocalDate to an Instant?
提问by user1643352
I work with the new DateTime API of Java 8.
我使用 Java 8 的新 DateTime API。
How to convert a LocalDate to an Instant? I get an exception with
如何将 LocalDate 转换为 Instant?我得到一个例外
LocalDate date = LocalDate.of(2012, 2, 2);
Instant instant = Instant.from(date);
and I don't understand why.
我不明白为什么。
采纳答案by JodaStephen
The Instant
class represents an instantaneous point on the time-line. Conversion to and from a LocalDate
requires a time-zone. Unlike some other date and time libraries, JSR-310 will not select the time-zone for you automatically, so you must provide it.
的Instant
类表示时间线的瞬时点。与 a 之间的转换LocalDate
需要时区。与其他一些日期和时间库不同,JSR-310 不会自动为您选择时区,因此您必须提供它。
LocalDate date = LocalDate.now();
Instant instant = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
This example uses the default time-zone of the JVM - ZoneId.systemDefault()
- to perform the conversion. See here for a longer answerto a related question.
此示例使用 JVM 的默认时区 - ZoneId.systemDefault()
- 来执行转换。有关相关问题的更长答案,请参见此处。
Update: The accepted answer uses LocalDateTime::toInstant(ZoneOffset)
which only accepts ZoneOffset
. This answer uses LocalDate::atStartOfDay(ZoneId)
which accepts any ZoneId
. As such, this answer is generally more useful (and probably should be the accepted one).
更新:接受的答案使用LocalDateTime::toInstant(ZoneOffset)
只接受ZoneOffset
. 这个答案使用LocalDate::atStartOfDay(ZoneId)
which 接受 any ZoneId
。因此,这个答案通常更有用(并且可能应该是公认的)。
PS. I was the main author of the API
附注。我是 API 的主要作者
回答by mdo
In order to convert it to an instant you need to have a LocalDateTime instance, e.g.:
为了将其转换为即时,您需要有一个 LocalDateTime 实例,例如:
LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC)