Along with lambda expression, virtual methods, streams and many other nice features, Java 8 has also updated a new Date and Time API which is maintained under the JSR-310. One of the greatest on this new API is that all the date and time related APIs are unified under the same package java.time. In my previous articles I have explained about the LocalDate and LocalTime .This example demonstrates how to convert from old date API to Java 8 API.
If you have any clarifications, please write it in the comments section or post it in our facebook page. You can read more articles on Java 8 here.
How To Convert From java.util.Date to Java 8 Date Time API?
With Java 8, java.util.Date class introduces new method toInstant() which directly converts to java.time.Instant. Once you have the Instant class, it is further easy for the developers to convert to java.time.LocalDateTime and then get the either LocalDate or LocalTime objects. Lets look at the example.
Example
package javabeat.net; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.Date; /** * Convert from old Date format to Java 8 APIs * * @author www.javabeat.net * */ public class ConvertOldDateToJava8 { public static void main(String[] args) { Date date = new Date(); System.out.println("Current Date in Old Date Object: " + date); Instant instant = date.toInstant(); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); LocalDate localDate = localDateTime.toLocalDate(); LocalTime localTime = localDateTime.toLocalTime(); System.out.println("LocalDate : " + localDate); System.out.println("LocalTime : " + localTime); } }
Output for the above program will be:
Current Date in Old Date Object: Sun Apr 12 10:05:47 IST 2015 LocalDate : 2015-04-12 LocalTime : 10:05:47.236