简体   繁体   中英

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.

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
  2. Date to LocalDate

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 . 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.
  2. Use org.threeten.bp.DateTimeUtils for conversions between legacy date-time classes and the classes in ThreeTen Backport.

Example of option 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

DateTimeUtils also has a toInstant(Date) method for the opposite conversion.

Link: DateTimeUtils documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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