September 29, 2022

Convert LocalDate to Date in Java

This post shows how to convert java.time.LocalDate to java.util.Date in Java.

For converting LocalDate to Date steps are as follows-

  1. Get the ZonedDateTime from the LocalDate by specifying the ZoneId.
  2. Convert that ZonedDateTime to Instant instance using toInstant() method.
  3. Pass instant to Date.from() method to get a java.util.Date instance.

If we have to write those steps elaborately then it can be done as follows-

LocalDate ld = LocalDate.now();
System.out.println("Local Date - " + ld);
ZonedDateTime zdt = ld.atStartOfDay(ZoneId.systemDefault());
Instant instant = zdt.toInstant();
Date date = Date.from(instant);
System.out.println("Date- " + date);
Output
Local Date - 2019-11-20
Date- Wed Nov 20 00:00:00 IST 2019

You can also do it in one line as given below-

LocalDate ld = LocalDate.now();
Date date = Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant());

That's all for the topic Convert LocalDate to Date in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment