Search code examples
javatype-mismatchdate-conversionjava.util.datethreetenbp

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

Solution

  • 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