In this post, we will see how to convert Date to LocalDate in java.
Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java.
Table of Contents
Using toInstant() method of Date class
You can convert Date to LocalDate using toInstant()
method of Date class. Since Instant
objects are time agnostic, you need to use atZone()
method to convert to derive LocalDate
from it.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog.entry; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; public class JavaDateToLocalDateUsingInstant { public static void main(String[] args) { Date date=new Date(); LocalDate localDate = convertDateToLocalDateUsingInstant(date); System.out.println("Local Date: "+localDate); } public static LocalDate convertDateToLocalDateUsingInstant(Date date) { return date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); } } |
Output:
Using toInstant() method of Date class
You can convert Date to LocalDate using toInstant()
method of Date
class. You can use Intant.ofEpochMilli(date.getTime())
to derive instant object and use atZone()
method to associate time zone to instant object.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.arpit.java2blog.entry; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; public class JavaDateToLocalDateUsingOfEpochMilli { public static void main(String[] args) { Date date=new Date(); LocalDate localDate = convertDateToLocalDateUsingOfEpochMilli(date); System.out.println("Local Date: "+localDate); } public static LocalDate convertDateToLocalDateUsingOfEpochMilli(Date date) { return Instant.ofEpochMilli(date.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDate(); } } |
Output:
Using java.sql.Date
You can convert Date to LocalDate using java.sql.Date
. In Java 8, there is new method toLocalDate()
added to java.sql.Date
class.`
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog.entry; import java.time.LocalDate; import java.util.Date; public class JavaDateToLocalDateUsingSQLDate { public static void main(String[] args) { Date date=new Date(); LocalDate localDate = convertDateToLocalDateUsingSQLDate(date); System.out.println("Local Date: "+localDate); } public static LocalDate convertDateToLocalDateUsingSQLDate(Date date) { return new java.sql.Date(date.getTime()).toLocalDate(); } } |
Output:
That’s all about how to convert Date to LocalDate in java