Java Convert LocalDate to Date
Tags: Java LocalDate Java Date Java 8
In this Java core tutorial we learn how to convert java.time.LocalDate object to java.util.Date object in Java programming language.
How to convert LocalDate to Date in Java
In Java to convert a LocalDate object to Date object we can follow these step
- Firstly convert LocalDate to a ZonedDateTime
- Secondly convert ZonedDateTime to Instant object
- And then create a new Date object from the Instant.
In the following Java program we show how to convert LocalDate to Date as the step by step above.
ConvertLocalDateToDateExample1.java
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public class ConvertLocalDateToDateExample1 {
public static void main(String... args) {
LocalDate localDate = LocalDate.of(2022, 7, 11);
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
Date date = Date.from(instant);
System.out.println("LocalDate: " + localDate);
System.out.println("Date: " + date);
}
}
LocalDate: 2022-07-11
Date: Mon Jul 11 00:00:00 ICT 2022
Or we can write the Java code in one line as below.
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
The following Java program to show how to LocalDate to Date with one line of code above.
ConvertLocalDateToDateExample2.java
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class ConvertLocalDateToDateExample2 {
public static void main(String... args) {
LocalDate localDate = LocalDate.of(2022, 7, 11);
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
System.out.println("LocalDate: " + localDate);
System.out.println("Date: " + date);
}
}
LocalDate: 2022-07-11
Date: Mon Jul 11 00:00:00 ICT 2022
Happy Coding 😊
Related Articles
Java Convert Date to LocalDate
Java Convert LocalDate to String
Java Convert LocalDate to LocalDateTime
Java Convert LocalDate to OffsetDateTime
Java Convert LocalDate to Epoch Day
Java Convert LocalDate to ZonedDateTime
Java Convert LocalDate to Calendar