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

George picture George · Oct 11, 2015 · Viewed 170.3k times · Source

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

George picture George · Oct 11, 2015

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 explicit setting of time zones because the local time zone is taken implicitly.

From docs:

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

The java.sql.Date subclasses java.util.Date so the result is a java.util.Date also.

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