How to Convert Between Date and LocalDateTime

In Java, you can convert between java.util.Date and java.time.LocalDateTime using the java.time API introduced in Java 8. Here’s how you can perform the conversions:


1. Converting Date to LocalDateTime

You need to use java.time.Instant and java.time.ZoneId to make this conversion. Here’s the process:

package org.kodejava.datetime;

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

public class DateToLocalDateTimeExample {
    public static void main(String[] args) {
        // Create a Date object
        Date date = new Date();

        // Convert Date to LocalDateTime
        LocalDateTime localDateTime = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        System.out.println("Date: " + date);
        System.out.println("LocalDateTime: " + localDateTime);
    }
}

2. Converting LocalDateTime to Date

To convert back from LocalDateTime to Date, again you will make use of Instant and ZoneId.

package org.kodejava.datetime;

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

public class LocalDateTimeToDateExample {
    public static void main(String[] args) {
        // Create a LocalDateTime object
        LocalDateTime localDateTime = LocalDateTime.now();

        // Convert LocalDateTime to Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

        System.out.println("LocalDateTime: " + localDateTime);
        System.out.println("Date: " + date);
    }
}

Explanation:

  1. Date to LocalDateTime:
    • Date.toInstant() converts the Date object into an Instant (a specific point in time).
    • .atZone(ZoneId.systemDefault()) adjusts the instant to your system’s default time zone.
    • .toLocalDateTime() converts the zoned date-time to a LocalDateTime.
  2. LocalDateTime to Date:
    • .atZone(ZoneId.systemDefault()) converts a LocalDateTime into a ZonedDateTime.
    • ZonedDateTime.toInstant() gets an Instant for the given date and time in the local zone.
    • Date.from(Instant) creates a Date object from the Instant.

By using these conversions, you can easily switch between the old java.util.Date and the modern java.time.LocalDateTime API.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.