What's the correct way to convert between java.sql.Date
and LocalDate
(Java8)?
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();