简体   繁体   English

获取错误:日期中的from(java.time.Instant)无法应用于(org.threeten.bp.instant)

[英]Getting error: from(java.time.Instant) in Date cannot be applied to (org.threeten.bp.instant)

I am trying to convert the org.threeten.bp.LocalDate to java.util.Date and I am getting the error mentioned in the question title. 我试图将org.threeten.bp.LocalDate转换为java.util.Date ,我收到问题标题中提到的错误。

I am using following for conversion: 我正在使用以下转换:

Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Error: 错误:

from(java.time.Instant) in Date cannot be applied to (org.threeten.bp.instant)

I am trying to convert 我想转换

  1. LocalDate to Date LocalDate到日期
  2. Date to LocalDate DateDate的日期

Your code is basically correct and would have worked with java.time.LocalDate , only not with the implementation of the same class in org.threeten.bp.LocalDate . 您的代码基本上是正确的,并且可以使用java.time.LocalDate ,但不能与java.time.LocalDate中的相同类的实现org.threeten.bp.LocalDate So your options are two: 所以你的选择是两个:

  1. Change all of your imports to use java.time instead of org.threeten.bp and stop using the backport. 更改所有导入以使用java.time而不是org.threeten.bp并停止使用backport。
  2. Use org.threeten.bp.DateTimeUtils for conversions between legacy date-time classes and the classes in ThreeTen Backport. 使用org.threeten.bp.DateTimeUtils进行遗留日期时间类与ThreeTen Backport中的类之间的转换。

Example of option 2.: 选项2的示例:

    LocalDate currentDate = LocalDate.now(ZoneId.of("America/Whitehorse"));
    Date d = DateTimeUtils.toDate(
            currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    System.out.println("" + currentDate + " was converted to " + d);

When running on my computer just now this snippet printed: 刚刚在我的电脑上运行时,这个片段打印出来了:

2019-06-25 was converted to Tue Jun 25 00:00:00 CEST 2019 2019-06-25被转换为Tue Jun 25 00:00:00 CEST 2019

DateTimeUtils also has a toInstant(Date) method for the opposite conversion. DateTimeUtils也有一个toInstant(Date)方法用于相反的转换。

Link: DateTimeUtils documentation 链接: DateTimeUtils文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM