How to convert Date to LocalDateTime in Java 8 - Example Tutorial

The LocalDateTime class has been introduced in Java 8 to represent both date and time values. It's local, so date and time are always in your local time zone. Since the java.util.Date has been widely used everywhere in many Java applications, you will often find yourself converting java.util.Date to LocalDate, LocalTime, and LocalDateTime classes of the java.time package. Earlier I have shown you how to convert Date to LocalDate and today, I am going to teach you how to convert Date to LocalDateTime in Java 8. The approach is the same. Since the equivalent class of java.util.Date in new Date and Time API in java.time.Instant, we first convert Date to Instance and then create LocalDateTime instance from that Instant using System's default timezone.

JDK 8 has added convenient toInstant() method on java.util.Date to interface old date and time API with a new one.

The key detail to note here is that the java.util.Date is not exactly the date but an instance of time (milliseconds passed from Epoch) and that's why it equates to an instance of the java.time.Instant object.

Another important thing to remember is that an Instant also does not contain any information about the time zone. Thus, to create a DateTime object from Instant, it is necessary to specify a timezone.

For LocalDateTime, this should be the default zone provided by ZoneId.systemDefault() method. 

If your application controls the timezone then you can use that here as well. The LocalDateTime class has a convenient factory method. LocalDateTime.ofInstant(), which takes both the instant and time zone.

If you are curious about important Java 8 features, you can also join The Complete Java MasterClass course on Udemy to learn more about key concepts of the new Date and Time API. It's one of the best courses to learn Java and also the most up-to-date, recently updated for the Java 11 version.




How to Convert Date to LocalDateTime in Java 8

Here are exact steps to convert Date to LocalDatetime:
  1.  Convert Date to Instant using the toInstant() method
  2.  Create LocalDateTime using the factory method ofInstant() by using System's default timezone.

Here is how you can convert java.util.Date to java.time.LocalDateTime in Java 8 with two lines of code.

Date today = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(today.toInstant(),
                                             ZoneId.systemDefault());

Now, if you want to convert the LocalDateTime back to java.util.Date, you need to go via ZonedDateTime class, which represents date and time value with the time zone.


And, here are the steps to convert a LocalDateTime to java.util.Date in Java:

1) Convert LocalDateTime to ZonedDateTime using the atZone() method
2) Convert ZonedDateTime to Instant

Here is the sample code to convert LocalDateTime to Date in Java 8:

ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date output = Date.from(zdt.toInstant())

If you want to learn the new Date and Time API from start to end, just join the Modern Java - Learn Java 8 features by coding it course on Udemy.  One of the best courses to learn new features of Java 8, including lambdas, streams, concurrency enhancement, and other worth noting features.

And, here is a nice slide to convert both Dates to LocalDateTime and vice-versa:

Date to LocalDateTime in Java8 Convert Example





Java Program to convert Date to LocalDateTime in Java 8

Now that we know the concept behind Date and LocalDateTime classes and steps to convert java.util.Date to java.time.LocalDateTime, let's see a complete working program to understand the idea better.

In this program, I have converted the current value of Date to equivalent LocalDateTime value in Java 8.

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

/**
 * Java Program to demonstrate how to convert Date to LocalDateTime class in
 * Java 8. Just remember that, the equivalent class of Date in 
 * new Date and Time
 * API is not LocalDateTime but the Instant.
 *
 * @author WINDOWS 8
 */
public class Java8Demo {

    public static void main(String args[]) {

        // converting java.util.Date to java.time.LocalDateTime
        Date now = new Date();
        Instant current = now.toInstant();
        LocalDateTime ldt = LocalDateTime.ofInstant(current, 
                                                 ZoneId.systemDefault());

        System.out.println("value of Date: " + now);
        System.out.println("value of LocalDateTime: " + ldt);

        // converting java 8 LocalDateTime to java.util.Date
        ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
        Date output = Date.from(zdt.toInstant());

        System.out.println("value of LocalDateTime: " + ldt);
        System.out.println("value of Date: " + output);

    }

}

Output
value of Date: Sat Mar 05 21:30:32 GMT+05:30 2016
value of LocalDateTime: 2016-03-05T21:30:32.601
value of LocalDateTime: 2016-03-05T21:30:32.601
value of Date: Sat Mar 05 21:30:32 GMT+05:30 2016

Note that the conversion from LocalDateTime to ZonedDateTime has the potential to introduce unexpected behavior. This is because not every local date-time exists due to Daylight Saving Time.

In autumn/fall, there is an overlap in the local timeline where the same local date-time occurs twice. In spring, there is a gap, where an hour disappears. See the Javadoc of atZone(ZoneId) for more definitions of what the conversion will do.

Similarly, if you convert a java.util.Date to a LocalDateTime and back to a java.util.Date, you may end up with a different instant due to Daylight Saving Time.


That's all about how to convert LocalDateTime to Date in Java 8 and vice-versa. Just remember that Date doesn't have any timezone information. It just holds milliseconds from Epoch in a long variable. It's the toString() method of Date that prints the Date value in the local timezone. That's why you need a time zone to convert the Date value to LocalDateTime or ZonedDateTime.



Other Java 8 tutorials you may like to explore
  • How to join String in Java 8 (example)
  • How to use forEach() method in Java 8 (example)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to convert List to Map in Java 8 (solution)
  • How to use peek() method in Java 8 (example)
  • Difference between abstract class and interface in Java 8? (answer)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • How to use peek() method in Java 8 (example)
  • How to sort the may by values in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 5 Free Courses to learn Java 8 and 9 (courses)

Thanks for reading this article so far. If you like this Java 8 tutorial then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a comment.

P.S.: If you just want to learn more about new features in Java 8 then please see the course What's New in Java 8. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API, and other miscellaneous changes.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.