Convert between LocalDate and sql.Date

JavaDateJava 8Java TimeConverters

Java Problem Overview


What's the correct way to convert between java.sql.Date and LocalDate (in both directions) in Java 8 (or higher)?

Java Solutions


Solution 1 - Java

The Java 8 version (and later) of java.sql.Date has built in support for LocalDate, including toLocalDate and valueOf(LocalDate).

To convert from LocalDate to java.sql.Date you can use

java.sql.Date.valueOf( localDate );

And to convert from java.sql.Date to LocalDate:

sqlDate.toLocalDate();

Time zones:

The LocalDate type stores no time zone information, while java.sql.Date does. Therefore, when using the above conversions, the results depend on the system's default timezone (as pointed out in the comments).

If you don't want to rely on the default timezone, you can use the following conversion:

Date now = new Date();
LocalDate current = now.toInstant()
                       .atZone(ZoneId.systemDefault()) // Specify the correct timezone
                       .toLocalDate();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmajaView Question on Stackoverflow
Solution 1 - JavamajaView Answer on Stackoverflow