Java 8 – How to convert LocalDate to java.sql.Date and sql Date to LocalDate

In this article, we will see examples to convert LocalDate to java.sql.Date and sql Date to LocalDate in Java 8.

convert java localdate to sql date

Java 8 introduced java.time.LocalDate to represent a Date without time.

With the Java 8 version, java.sql.Date was also updated to provide support for LocalDate, including toLocalDate and valueOf(LocalDate) methods.

 

Convert java.time.LocalDate to java.sql.Date

We can convert from LocalDate to java.sql.Date using :


java.sql.Date.valueOf( localDate )

Here is an example :

package com.topjavatutorial;

public class DateUtilDemo {

  public static void main(String[] args) {
    
    java.time.LocalDate date = java.time.LocalDate.now();
    System.out.println("java.time.LocalDate = " + date);
    
    java.sql.Date sqlDate = java.sql.Date.valueOf(date);
    System.out.println("java.sql.Date = " + sqlDate);

  }
}

Output :

java.time.LocalDate = 2016-12-11
java.sql.Date = 2016-12-11

 

Convert java.sql.Date to java.time.LocalDate

We can convert from java.sql.Date to LocalDate using :


sqlDate.toLocalDate();

Here is an example :

    java.sql.Date sqlDate = java.sql.Date.valueOf("2016-11-12");
    System.out.println("java.sql.Date = " + sqlDate);

    java.time.LocalDate localDate = sqlDate.toLocalDate();
    System.out.println("java.time.LocalDate = " + localDate);

Output :

java.sql.Date = 2016-11-12
java.time.LocalDate = 2016-11-12

 

© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags