3 Ways to Convert java.sql.date to/from Localdate in java: examples
java.sql.Date
is a date class used to store date, time, and timezone information.
LocalDate
is stores Date only without time and timezone information This short tutorial talks about how to convert SQL date to /from localdate in java with examples
How to convert LocalDate to java.sql.date in java
This example parse LocalDate to java.sql.date in java with example.
LocalDate has the valueOf
method which converts to SQL date.
import java.sql.Date;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate localDate = LocalDate.of(2020, 07, 27);
System.out.println(localDate); //2020-07-27
Date sqlDate = Date.valueOf(localDate);
System.out.println(sqlDate); //2020-07-27
}
}
How to convert java.sql.Date to LocalDate
This example shows multiple ways we can convert SQL date to LocalDate java with example.
using toInstant() method
Create java.util.Date object to get current date
Converted currentDate to LocalDate using default zone with toInstant method.
Date currentDate = new Date(System.currentTimeMillis());
LocalDate current = currentDate.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
- toLocalDate method
java.sql.Date has the toLocaleDate method which returns the LocalDate object.
It is a simple example
import java.sql.Date;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
Date currentDate = new Date(System.currentTimeMillis());
System.out.println(currentDate);
LocalDate ld=currentDate.toLocalDate();
System.out.println(ld);
}
}