Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert between LocalDate and sql.Date [duplicate]

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

like image 723
maja Avatar asked Apr 20 '15 14:04

maja


1 Answers

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(); 
like image 71
maja Avatar answered Oct 05 '22 07:10

maja