Convert LocalDateTime to java.util.Date



In this article, we will learn how to convert a LocalDateTime object to a java.util.Date object in Java. The conversion is essential when working with modern and legacy date/time APIs, ensuring compatibility between them.

LocalDateTime Class

The java.time.LocalDateTime class represents a specific date and time without including any time-zone details, following the ISO-8601 calendar system. For instance, it can represent values like 2007-12-03T10:15:30. This makes it ideal for scenarios where time-zone information is not required, focusing solely on the local date and time.

Java Date class

The java.util.Date class represents a specific moment in time, accurate to the millisecond. It's commonly used in Java, though newer classes like LocalDateTime are often preferred for handling dates and times.

Steps to convert LocalDateTime to java.util.Date

Following are the steps to convert LocalDateTime to java.util.Date ?

  • Import the necessary classes:
    • java.time.LocalDateTime for modern date/time handling.
    • java.time.ZoneId and java.time.Instant for time zone and instant conversions.
    • java.util.Date for legacy date compatibility.
  • Create a LocalDateTime object using the now() method.
  • Convert the LocalDateTime to an Instant using the atZone() method with the system's default time zone.
  • Convert the Instant to a java.util.Date using the Date.from() method.
  • Print the Instant and the Date to verify the conversion

Java program to convert LocalDateTime to java.util.Date

Following are the steps to convert LocalDateTime to java.util.Date ?

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

Output

Instant = 2019-04-19T04:34:31.271973Z
Date = Fri Apr 19 10:04:31 IST 2019

Code explanation

The LocalDateTime.now() creates the current date and time. The atZone() method associates the LocalDateTime with the system's default time zone (ZoneId.systemDefault()), and the toInstant() method converts it to an Instant object. Finally, the Date.from() method takes this Instant and produces a java.util.Date object. Both the Instant and Date objects are printed for verification.

Updated on: 2024-11-29T19:11:15+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements