How to convert LocalDate to Util Date and vice versa in Java?

Photo by Moose Photos on Pexels.com

Java 8 introduced LocalDate to represent date without the time information .

But sometimes we may need to convert LocalDate to the legacy java util Date in our code .

This post explains how to convert from LocalDate to java.util.Date and vice versa.

The below code converts local date to Util Date:

LocalDate localDate = LocalDate.now();

Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();

java.util.Date utilDate = Date.from(instant);



And the below code converts the Util Date back to Local Date:

LocalDate localDateConverted = LocalDate.ofInstant(utilDate.toInstant(), ZoneId.systemDefault());

A brief explanation of the code:

Local Date -> Util Date:

The basic mechanism used above to convert between the different date types is to first generate the instant.

Java has its own time scale named Java Time Scale and Instant represents a moment in this time scale.

To generate Util Date from Instant , java.util.Date API provides the method Date.from(instant).

To generate the instant ,

  • Convert Local Date to Local Date Time using the method atStartOfDay() which returns the local date time at midnight
  • Then convert the local date time to Zone Date time using atZone() method with the default time zone (ZoneId.systemDefault())
  • Use the returned ZonedDateTime to generate the instant using the method toInstant()

Util Date -> Local Date

Local Date provides an API to generate Local Date from Instant :

LocalDate.ofInstant(instant, zone) .

Generate the instant by calling the method toInstant() on util date and then pass it to the above method along with the default zone (ZoneId.systemDefault())

In the above code LocalDate.ofInstant() was added in Java 9. If you are using earlier versions use :

utilDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

Here is the entire code which converts date from LocalDate to java.util.Date and back again:

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateToDateConverter {

	public static void main(String a[]) {

		LocalDate localDate = LocalDate.now();

		System.out.println(localDate);


		Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();

		java.util.Date utilDate  = Date.from(instant);

		System.out.println(utilDate);

		LocalDate localDateConverted = LocalDate.ofInstant(utilDate.toInstant(), ZoneId.systemDefault());

		System.out.println(localDateConverted);
	
	}

}

Below is the output:

2020-04-07
Tue Apr 07 00:00:00 IST 2020
2020-04-07


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading