Convert LocalDate to java.util.Date in Java



Suppose a date is given in LocalDate format, our task is to write a Java program that converts it into java.util.Date. For this problem, we need to add time information to the LocalDate by combining it with a time, such as midnight, or a timezone.

Both LocalDate and java.util.Date classes are used to represent a date in Java. But, the LocalDate class, introduced with the release of Java8, represents a date without timezone information, whereas, the Date class is mutable and used for representing date and time with timezone.

Let's understand the problem statement with an example.

Example Scenario:

Input: localdate = 2019-04-19;
Output: date = Fri Apr 19 00:00:00 IST 2019;

By Converting LocalDate into Instant

In this approach, we first convert the LocalDate to Instant using toInstant() method and then, we use the Date.from() method to convert Instant into Date.

Example

The following Java program shows how to convert LocalDate to Date.

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Demo {
   public static void main(String[] args) {
      LocalDate date = LocalDate.now();
      System.out.println("LocalDate = " + date);
      Instant i = date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
      System.out.println("java.util.Date = " + java.util.Date.from(i));
   }
}

On executing, this code produce the following result ?

LocalDate = 2019-04-19
java.util.Date = Fri Apr 19 00:00:00 IST 2019

By Converting LocalDate into Calendar

Here, we first convert the LocalDate to Calendar using the set() method, and then we convert the Calendar to Date using the getTime() method to obtain the final result.

Example

Let's see the practical demonstration ?

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class LocalDateToDateUsingCalendar {
   public static void main(String[] args) {
      LocalDate locDate = LocalDate.now();
	  System.out.println("LocalDate = " + locDate);
      Calendar calendar = new GregorianCalendar();
      calendar.set(locDate.getYear(), locDate.getMonthValue() - 1, locDate.getDayOfMonth());
      Date date = calendar.getTime();
      System.out.println("java.util.Date = " + date);
   }
}

On running this code, you will get the following output ?

LocalDate = 2024-09-02
java.util.Date = Mon Sep 02 08:24:09 GMT 2024
Updated on: 2024-09-11T11:12:58+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements