In this post we will look how to convert Date to LocalDate in Java. We will also convert LocalDateTime to Date.
1. Convert Date to LocalDate
Java 8 introduces a new API to work with date and time. In this section, let’s see how to convert Date to LocalDate with Java.
1.1 Date To LocalDate
Date date = new Date();
LocalDate localDate = Instant.ofEpochMilli(date.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDate();
System.out.println(date); //Thu Oct 01 16:10:58 PDT 2020
2. Convert LocalDate to Date
There might be some use case where we like to convert LocalDate to Date in Java. This section will take a look at this option.
LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
System.out.println(date); //Thu Oct 01 00:00:00 PDT 2020
Date date2 = Date.from(localDate.atStartOfDay(
ZoneId.systemDefault())
.toInstant());
System.out.println(date2); //Thu Oct 01 00:00:00 PDT 2020
3. DateUtils for Conversion
It’s always a best to create your own small utility class to perform the date conversion. Let’s write a small utility class to perform the following for us, and we can use it throughout our project.
- Convert Date to LocalDate using system default
ZoneId
. - Date to LocalDate using supplied
ZoneId
. - Convert
LocalDate
back toDate
in Java using
package com.javadevjournal.date;
import java.time.*;
import java.util.Date;
public final class JDJDateUtils {
public static LocalDate convertToLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDate(Date date, ZoneId zoneId) {
return Instant.ofEpochMilli(date.getTime())
.atZone(zoneId)
.toLocalDate();
}
public static Date convertToDate(LocalDate date) {
return Date.from(date
.atStartOfDay().atZone(
ZoneId.systemDefault())
.toInstant());
}
public static Date convertToDate(LocalDate date, ZoneId zoneId) {
return Date.from(date
.atStartOfDay().atZone(
zoneId)
.toInstant());
}
}
Let’s see how to use this utility class for better readability and maintenance.
Date date = new Date();
LocalDate localDate = JDJDateUtils.convertToLocalDate(date);
System.out.println(localDate); //2020-10-01
LocalDate localDate1 = JDJDateUtils.convertToLocalDate(date, ZoneId.of("Asia/Kolkata"));
System.out.println(localDate1); //2020-10-02
LocalDate localDate3 = LocalDate.now();
Date date1 = JDJDateUtils.convertToDate(localDate3);
System.out.println(date1); //Thu Oct 01 00:00:00 PDT 2020
Date date2 = JDJDateUtils.convertToDate(localDate3, ZoneId.of("Asia/Kolkata"));
System.out.println(date2); //Wed Sep 30 11:30:00 PDT 2020
Summary
In this post, we saw how to convert Date to LocalDate in Java and vice versa. We also created a small utility class to handle date conversion more efficiently and avoid code duplication. The source code is available on the GitHub.