我正在尝试将 org.thirden.bp.LocalDate
转换为 java.util.Date
,并且收到问题标题中提到的错误。
我使用以下进行转换:
Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
错误:
from(java.time.Instant) in Date cannot be applied to (org.threeten.bp.instant)
我正在尝试转换
- 本地日期至今
- 日期到本地日期
最佳答案
您的代码基本上是正确的,并且可以与 java.time.LocalDate
一起使用,但不能与 org. Threeten.bp.LocalDate
中同一类的实现一起使用。所以你的选择有两个:
- 将所有导入更改为使用
java.time
而不是org. Threeten.bp
并停止使用向后移植。 - 使用
org. Threeten.bp.DateTimeUtils
在旧版日期时间类与 ThreeTen Backport 中的类之间进行转换。
选项 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);
刚刚在我的计算机上运行时,打印了以下代码段:
2019-06-25 was converted to Tue Jun 25 00:00:00 CEST 2019
DateTimeUtils
还具有用于相反转换的 toInstant(Date)
方法。
关于java - 日期中出现错误 : from(java. time.Instant) 无法应用于 (org. Threeten.bp.instant),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729718/