2

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
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
AkshayT
  • 2,901
  • 2
  • 28
  • 32

1 Answers1

3

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • I switched to `JodaTime` and completely removed the `org.threeten.bp` library. But thanks for the answer. I will try it and if it works I will accept the answer. – AkshayT Jun 25 '19 at 15:21
  • 1
    Glad you got something to work. Joda-Time officially recommends: *Users are now asked to migrate to `java.time` (JSR-310).* So you should prefer java.time (either built-in or through the backport). More on [the Joda-Time home page](https://www.joda.org/joda-time/). – Ole V.V. Jun 25 '19 at 15:33