Table of Contents
In this article, we will see how to convert LocalDate to Instant in Java.
Java LocalDate to Instant
Instant
class provides an instantaneous point in time. When you want to convert LocalDate to Instant, you need to provide time zone.
Using toInstant() wth ZoneId
ZoneDateTime’s toInstant()
method can be used to convert LocalDate to Instant. You need to provide ZoneId
before doing the conversion.
- Get
LocalDate
object withLocalDate.now()
- Create
ZoneId
instance based on the Locale - Pass
ZoneId
toLocalDate
‘satStartOfDay()
to get ZoneDateTime. - Use
ZoneDateTime
‘stoInstant()
method to convert LocalDate to Instant in Java.
If you want to have default timezone, you can use ZoneId.systemDefault()
. It will provide you default timezone of JVM.
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; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; public class JavaLocalDateToInstant { public static void main(String[] args) { // Get LocalDate object LocalDate date = LocalDate.now(); // Get default timezone ZoneId zoneId = ZoneId.systemDefault(); // Convert LocalDate to Instant using toInstant() method Instant instant = date.atStartOfDay(zoneId).toInstant(); // Print Instant System.out.println("Instant obj: "+instant); } } |
Output:
Further reading:
Using toInstant() with ZoneOffset
You can pass ZoneOffset
to ZoneDateTime’s toInstant()
method to convert LocalDate to Instant in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package org.arpit.java2blog; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; public class JavaLocalDateToInstant { public static void main(String[] args) { // Get LocalDate object LocalDate localDate = LocalDate.now(); // Convert LocalDate to Instant with ZoneOffSet Instant instant = localDate.atStartOfDay().toInstant(ZoneOffset.UTC); // Print Instant System.out.println("Instant obj: "+instant); } } |
Output:
That’s all about how to convert LocalDate to Instant in Java.