George George - 1 year ago 84
Java Question

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

Is there a simple way to convert a

(introduced with Java 8) to

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 Source

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();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download