Wednesday, February 1, 2023

3 Examples to Convert Date to LocalDate in Java 8? Tutorial

One of the great features of Java 8 is the new Date and Time API which is intended to fix existing issues related to mutability and thread-safety with existing java.util.Date class. But given java.util.Date is used very heavily across all the Java applications, you will often end up with a situation where you need to convert java.uti.Date to java.time.LocalDate while working in Java 8. Unfortunately there is no toLocalDate() method in the java.util.Date class. Though, you can easily convert Date to LocalDate if you are familiar with how new and old API classes map to each other.

The equivalent class of java.util.Date in new Date and Time API in java.time.Instant because Date actually represents an instance of time-line, not a date. That's why you also have a toInstant() method on the Date class.

Despite its name, java.util.Date represents an instant on the timeline, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).

The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion:

Date input = new Date();
Instant instant = input.toInstant();

A java.util.Date instance has no concept of time-zone. This might seem strange if you call toString() on a java.util.Date, because the toString() is relative to a time-zone. However, that method actually uses Java's default time-zone on the fly to provide the string. The time zone is not part of the actual state of java.util.Date.

An Instant also does not contain any information about the time zone. Thus, to convert from an Instant to a LocalDate it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault() - or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone() method to apply the time-zone.

This is a very important concept and if you don't know much about Date and Time in Java, I suggest you first go through a comprehensive Java course like The Complete Java MasterClass on Udemy to learn in a structured way. It's one of the most up-to-date and comprehensive courses.




3 Ways to convert java.util.Date to java.time.LocalDate in Java 8

Now that you know the basic concepts of Date and LocalDate class and knows the challenges behind converting Date to LocalDate and vice-versa, it is now time to see some practical code examples to convert java.util.Date to java.time.LocalDate in Java.


1. Using Instance and ZonedDateTime

So this is our first method to convert Date to LocalDate in Java. In this example, I have used the Instance and ZondeDateTime classes. In this example, we first convert Date To Instance using the toInstant() method which is added into java.util.Date class.

Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());

A ZonedDateTime contains a state consisting of the local date and time, time-zone, and the offset from GMT/UTC. As such the date - LocalDate - can be easily extracted using toLocalDate():

Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();




2.  Using Instant and Date.getTime()

This is another way to convert the old Date to a new LocalDate instance in Java. In this method, you use the Instance.ofEpochMilli() method to create a ZonedDateTime and then you convert that to LocalDate using the built-in toLocalDate() method as shown below:

Date date = new Date (System.currentTimeMillis());
LocalDate ld = Instant.ofEpochMilli(date.getTime())
                      .atZone(ZoneId.systemDefault()).toLocalDate()




3. Using java.sql.Date 

This is the third and the easiest way to convert a java.util.Date to LocalDate in Java. In this example, we first convert java.util.Date to java.sql.Date which just contains date without the time and then we use toLocalDate() method added on java.sql.Date to create a LocalDate object, easy isn't it?

Here is the code:

LocalDate ld = new java.sql.Date( new java.util.Date().getTime() )
                                .toLocalDate();

You can see here we have used the technique you have learned while converting the java.util.Date to SQL date and once you have java.sql.Date you can directly call the toLocalDate() method, which makes it really easy.

If you are thinking about how this is possible, it is possible because unlike java.util.Date which contains both Date and Time portion,  both java.sql.Date and java.time.LocalDate doesn't contain any time portion.

In other words, here we are just stripping out time portion of java.util.Date by converting into SQL date and then converting to LocalDate.  And it simplest realization: LocalDate.of(getYear() + 1900, getMonth() + 1, getDate()) because year starts from 1900 and month are zero-based in old API

If you are wondering how does a new Date and Time API looks, here is a nice diagram which shows class hierarchy of Java 8 Date and Time API:

3 Ways to convert java.util.Date to java.time.LocalDate in Java 8



That's all about how to convert java.util.Date to java.time.LocalDate in Java 8. This is a very common task for Java programmers to write code every day. I strongly suggest you understand the concepts and learn the techniques demonstrated in this article to avoid using Google every time you need to convert an old Date to a new Local Date object. It may seem difficult the first time, but once you understand the API and how it works, it's very easy to remember.


Other Java 8  and Date Time tutorials You may like

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

P. S. - If you are looking for some free courses to learn recent changes on Java 8 and Java 9 then you can also see this list of Free Java 8 and 9 Courses for Programmers.

No comments:

Post a Comment

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