Convert Instant to LocalDate in Java [2021]
Instant to LocalDate can be converted using 3 methods
- Using Instant.atZone()
- Using Instant.atOffset()
- Using LocalDateTime.ofInstant()
Here are the examples for all the three methods
Convert Instant to LocalDate
1. Using Instant.atZone()
//Using Instant.atZone()
Instant instant1 = Instant.now();
LocalDate localDate1 = instant1.atZone(ZoneId.systemDefault())
.toLocalDate();
System.out.println(localDate1);
//2020-07-07
2. Using Instant.atOffset()
//Using Instant.atOffset()
Instant instant2 = Instant.now();
LocalDate localDate2 = instant2.atOffset(ZoneOffset.UTC)
.toLocalDate();
System.out.println(localDate2);//2020-07-07
3. Using LocalDateTime.ofInstant()
//Using LocalDateTime.ofInstant()
Instant instant3 = Instant.now();
LocalDate localDate3= LocalDateTime.ofInstant(instant3, ZoneOffset.UTC)
.toLocalDate();
System.out.println(localDate3);//2020-07-07
Example:
Here is the full Example for all the three methods to Convert Instant to LocalDate:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class InstantToLocalDateEx1 {
public static void main(String[] args) {
//Using Instant.atZone()
Instant instant1 = Instant.now();
LocalDate localDate1 = instant1.atZone(ZoneId.systemDefault())
.toLocalDate();
System.out.println("Using Instant.atZone() : "+ localDate1);//2020-07-07
//Using Instant.atOffset()
Instant instant2 = Instant.now();
LocalDate localDate2 = instant2.atOffset(ZoneOffset.UTC)
.toLocalDate();
System.out.println("Using Instant.atOffset() : "+localDate2);//2020-07-07
//Using LocalDateTime.ofInstant()
Instant instant3 = Instant.now();
LocalDate localDate3= LocalDateTime.ofInstant(instant3, ZoneOffset.UTC)
.toLocalDate();
System.out.println("Using LocalDateTime.ofInstant() : "+localDate3);//2020-07-07
}
}
Output:
Using Instant.atZone() : 2020-07-07
Using Instant.atOffset() : 2020-07-07
Using LocalDateTime.ofInstant() : 2020-07-07
Conclusion:
In this tutorial, we have covered how to convert Instant to LocalDate in Java using 3 methods- Using Instant.atZone()
- Using Instant.atOffset()
- Using LocalDateTime.ofInstant()
- Using Instant.atZone()
- Using Instant.atOffset()
- Using LocalDateTime.ofInstant()
Comments
Post a Comment
If you have any doubts, Please let me know.