George George - 1 month ago 12
Java Question

LocalDate to java.util.Date and vice versa simpliest conversion?

Is there a simple way to convert a

LocalDate
(introduced with Java 8) to
java.util.Date
object?

By 'simple', I mean simpler than this:

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());


which seems a bit awkward to me.

Since we are interested only in the date portion and there is no timezone information in neither of the objects, why introduce time zones explicitly? The midnight time and the system default timezone should be taken implicitly for the conversion.

Answer

Actually there is. There is a static method valueOf in the java.sql.Date object which does exactly that. So we have

java.util.Date date = java.sql.Date.valueOf(localDate);

and that's it. No time zones, no complications. The java.sql.Date subclasses java.util.Date so the result is a java.util.Date also.

As stated in the documentation:

The provided LocalDate is interpreted as the local date in the local time zone.

And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:

LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();