In this post, we will see how to convert LocalDateTime to Date. Java 8 has introduced a lot of new APIs for Date and time.
Table of Contents
There can be many ways to convert Java LocalDateTime to date.
Using Instant object
You can convert LocalDateTime to date using Instant object which we can from ZonedDateTime. Here is the code for the same:
|
1 2 3 4 5 6 7 |
Date convertLocalDateTimeToDateUsingInstant(LocalDateTime dateToConvert) { return java.util.Date .from(dateToConvert.atZone(ZoneId.systemDefault()) .toInstant()); } |
Using TimeStamp
This is easiest way to convert LocalDateTime to date in Java 8. We can use java.sql.Timestamp to convert LocalDateTime to Date.
The easiest way of getting a java.util.Date from LocalDateTime is to use an extension to the java.sql.Timestamp – available with Java 8:
|
1 2 3 4 5 |
public Date convertLocalDateTimeToDateUsingTimestamp(LocalDateTime dateToConvert) { return java.sql.Timestamp.valueOf(dateToConvert); } |
Here is complete program to convert between LocalDateTime to Date.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package org.arpit.java2blog; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; public class LocalDateTimeToDateMain { public static void main(String[] args) { LocalDateTime ldt = LocalDateTime.now(); Date dt1=convertLocalDateTimeToDateUsingInstant(ldt); System.out.println(dt1); System.out.println("====================="); Date dt2=convertLocalDateTimeToDateUsingTimestamp(ldt); System.out.println(dt2); } public static Date convertLocalDateTimeToDateUsingInstant(LocalDateTime localDateTime) { return Date .from(localDateTime.atZone(ZoneId.systemDefault()) .toInstant()); } public static Date convertLocalDateTimeToDateUsingTimestamp(LocalDateTime localDateTime) { return Timestamp.valueOf(localDateTime); } } |
Output:
=====================
2019-04-14 00:47:05.179772
That’s all about Java LocalDateTime to Date in Java 8.