Convert between LocalDate to java.sql.Date

Java 8 examples to convert from LocalDate to java.sql.Date and vice versa.

LocalDate to java.sql.Date

Use java.sql.Date.toLocalDate() method to get java.sql.Date from LocalDate.

import java.time.LocalDate;
import java.util.Date;

public class Main 
{
	public static void main(String[] args) 
	{
		//Get SQL date instance 
		java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
		
		//Get LocalDate from SQL date
		LocalDate localDate = sqlDate.toLocalDate();
		
		System.out.println( localDate );	//2018-07-15
	}
}

java.sql.Date to LocalDate

Use java.sql.Date.valueOf() method to get LocalDate from Sql date.

import java.time.LocalDate;

public class Main 
{
	public static void main(String[] args) 
	{
		//Local date instance
		LocalDate localDate = LocalDate.now();
		
		//Get LocalDate from SQL date
		java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
		
		System.out.println( sqlDate );	//2018-07-15
	}
}

Happy Learning !!

References:

  1. LocalDate Javadoc
  2. SQL Time JavaDoc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.