javadatejava-8java-timeconverters

Convert between LocalDate and sql.Date


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


Solution

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

    (Edit: Apparently, this conversion is a bad practice. See https://stackoverflow.com/a/40143687/2224996 for a better approach and a more detailed explanation).

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