Prior to Java 8 for handling time and dates we had Date, Calendar, TimeStamp (java.util) but there were several performance issues as well as some methods and classes were deprecated, so Java 8 introduced some new concepts Date and Time APIs’ (also known as Joda time APIs’) present in java.time package.
Java 7: Date, Calendar, TimeStamp present inside java.util package.
Java 8: Time Date APIs’ present inside the java.time package.
Different ways to Convert java.util.Date to java.time.LocalDate:
- Using Instance and ZonedDateTime
- Using Instant and Date.getTime()
- Using ofInstant() and ZoneId.systemDefault()
Method 1: Using Instance and ZonedDateTime
- First we will convert the date object to an instant object.
- Every instant object is associated with the zoneId so we need to give the zoneId.
- At last we will convert it into LocalDate object.
- In this program, we will convert the date object into instant using toInstant() method which returns instant object and takes no parameters.
- Now we need to assign zoneId to it using atZone() method in this we need to pass the zone Id as a parameter for default we can use ZoneId.systemDefault().
- At last, we will convert it into a LocalDate object using the toLocalDate() method.
Method 2: Using Instant and Date.getTime()
This approach is almost similar to the first one the only difference will be the way the instant object will be created.
- Here we will use Instant.ofEpochMilli() method, it takes date as an argument.
- After that again we will use atZone() method for adding the ZoneId followed by toLocalDate() method to get the LocalDate Object.
- It is the easiest approach we will use Java 9’s ofInstant() method of LocalDate class it takes two parameters.
- A first parameter is an instant object of date and the second is ZoneId.
- Here in the first argument, we will use toInstant() method to get the instant object and for the second argument we will use ZoneId.systemDefault().
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.