In this post, we will see how to convert LocalDate
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 LocalDate
to Date
using Instant
object which we can from Zone
. Here is the code for the same:
1 2 3 4 5 6 7 |
Date public static Date convertToDateUsingInstant(LocalDate date) { return java.util.Date.from(date.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant()); } |
Using java.sql.Date
The easiest way to convert LocalDate to Date is to use valueOf()
method from java.sql.Date
. You should prefer first approach because java.util.Date
is meant for database layer and may change the dependency later in further java versions.
1 2 3 4 5 |
public static Date convertToDateUsingDate(LocalDate date) { return java.sql.Date.valueOf(date); } |
Here is complete program to convert between LocalDate
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 |
package org.arpit.java2blog; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; public class LocalDateToDateMain { public static void main(String[] args) { LocalDate ld = LocalDate.now(); Date dt1=convertToDateUsingInstant(ld); System.out.println("Using Instant:"+dt1); System.out.println("====================="); Date dt2=convertToDateUsingDate(ld); System.out.println("Using java.sql.Date: "+dt2); } public static Date convertToDateUsingDate(LocalDate date) { return java.sql.Date.valueOf(date); } public static Date convertToDateUsingInstant(LocalDate date) { return java.util.Date.from(date.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant()); } } |
Output:
=====================
2021-01-07
That’s all about Java LocalDate to Date in Java 8.