In Java, a date is represented by mainly 3 classes:
java.time.LocalDate: is part of the new Java 8 Date Time API. It only contains the date parts (day, month, year) and does not contain the time part (hour, minute and second).
java.util.Date: It is a legacy class used before Java 8 version. It contained the date as well as the time parts. It stores the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT).
java.sql.Date: It is also a legacy class and a subclass of java.util.Date. It is specifically designed to work with databases through the JDBC API. It can be used as SQL dates and pass dates between Java and SQL databases without losing the time information. It overrides the methods of java.util.Date to handle only the date part, effectively setting the time component to midnight (00:00:00).
In this tutorial, we will learn to convert from
java.sql.Date and vice versa.
1. java.sql.Date -> LocalDate
java.sql.Date.toLocalDate() method to get
LocalDate from a
In the following example, we are first creating an instance of java.sql.Date. In our application, we can get it from the database. Next, we call sqlDate.toLocalDate() to get the LocalDate instance.
//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 ); //2022-01-15
2. Convert LocalDate to java.sql.Date
java.sql.Date.valueOf() method to get SQL date from a
In the following example, we are first creating an instance of java.time.LocalDate. In our application, we can get it from a method or create outselve. Next, we call sqlDate.valueOf() to get the Date instance. Note that valueOf() is a static method so it can be directly called from the class reference.
//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 ); //2022-01-15
Happy Learning !!