In this article, we will see how to convert Instant to LocalDate in java.
Using ofInstant method [ Java 9+]
Java 9 has introduced static method ofInstant()
method in LocalDate
class. It takes Instant
and ZoneId
as input and returns LocalDate
object.
1 2 3 |
public static LocalDate ofInstant(Instant instant,ZoneId zone) |
Let’s see with the help of 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 25 |
package org.arpit.java2blog; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; public class InstantToLocalDate { public static void main(String[] args) { // Create Instant object Instant instant = Instant.parse("2022-01-23T00:00:00Z"); // Get ZoneID ZoneId zone = ZoneId.of("Europe/London"); // Convert Instant to LocalDate using ofInstant method LocalDate localDate = LocalDate.ofInstant(instant, zone); // Print LocalDate System.out.println("LocalDate Obj: "+localDate); } } |
Output:
Further reading:
Using ZoneDateTime’s toLocalDate() [Java 8]
- Get
Instant
object which you want to convert to LocalDate. - Create
ZoneId
instance based on Location. - Pass
ZoneId
toatZone()
method to getZoneDateTime
. - Call
toLocalDate()
onZoneDateTime
object to getLocalDate
.
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.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; public class InstantToLocalDate { public static void main(String[] args) { // Create Instant object Instant instant = Instant.parse("2022-01-23T00:00:00Z"); // Get ZoneID ZoneId zoneId = ZoneId.of("Europe/London"); // Get zoneDateTime using Instant's atZone() method ZonedDateTime zonedDateTime = instant.atZone(zoneId); // Convert Instant to LocalDate using toLocalDate method LocalDate localDate = zonedDateTime.toLocalDate(); // Print LocalDate System.out.println("LocalDate Obj: "+localDate); } } |
Output:
That’s all about how to convert Instant to LocalDate in java.