Java 8 - 将 LocalDate 转换为 ZonedDateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32001716/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:54:11  来源:igfitidea点击:

Java 8 - Convert LocalDate to ZonedDateTime

javajava-8java-time

提问by SelfTaught

I'm new to java.time package. I have a LocalDate 2015-12-10. I need to convert this to ZonedDateTime. Time should be 00:00:00 and Zone is ZoneOffset.UTC.

我是 java.time 包的新手。我有一个 LocalDate 2015-12-10。我需要将其转换为 ZonedDateTime。时间应为 00:00:00,Zone 为 ZoneOffset.UTC。

After conversion, ZonedDateTime should be 2015-12-10T00:00:00+02:00.

转换后, ZonedDateTime 应为 2015-12-10T00:00:00+02:00。

I'm storing the LocalDate in a variable called startDate.

我将 LocalDate 存储在一个名为 startDate 的变量中。

I tried:

我试过:

ZonedDateTime.ofInstant(Instant.from(startDate), ZoneOffset.UTC)

but get the error

但得到错误

java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: 2015-12-10 of type java.time.LocalDate]

java.time.DateTimeException: 无法从 TemporalAccessor 获取 Instant: 2015-12-10 类型 java.time.LocalDate]

I also tried:

我也试过:

startDate.atStartOfDay().atZone(ZoneOffset.UTC)

This gives unexpected results.

这会产生意想不到的结果。

I looked at the API and tried a few other methods, but no luck so far.

我查看了 API 并尝试了其他一些方法,但到目前为止没有运气。

Is there any other way to convert LocalDate to ZonedDateTime?

有没有其他方法可以将 LocalDate 转换为 ZonedDateTime?

采纳答案by JodaStephen

When converting less specific objects to more specific ones, use the 'at' methods:

将不太具体的对象转换为更具体的对象时,请使用“at”方法:

ZonedDateTime zdt = startDate.atStartOfDay(ZoneOffset.UTC);

Passing in the UTC offset will not get a result of +02:00 however, which suggests you are trying to achieve something else.

但是,传入 UTC 偏移量不会得到 +02:00 的结果,这表明您正在尝试实现其他目标。

回答by Luc S.

I supose the issue isn't relevant anymore but for google-purposes:

我认为这个问题不再相关,但出于谷歌的目的:

  LocalDate localDate = LocalDate.parse("2017-07-22");      
  ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
  // => 2017-07-22T00:00+05:30[Asia/Kolkata]

source https://beginnersbook.com/2017/10/java-convert-localdate-to-zoneddatetime/

来源 https://beginnersbook.com/2017/10/java-convert-localdate-to-zoneddatetime/