Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Instant to LocalDate

I have an Instant coming from a source that should, according to the specs, be a LocalDate, but don't see any methods in the LocalDate class to convert the Instant to a LocalDate.

What is the best way to do this?

like image 951
JL Gradley Avatar asked Sep 10 '18 20:09

JL Gradley


People also ask

How do I change from instant to LocalDate?

Instant instant = Instant. now(); LocalDate localDate = LocalDate. ofInstant(instant, ZoneOffset. UTC);

How do you convert instant to timezone?

Conversion Now we will call the atZone() method on the instant object to convert it to a ZonedDateTime object. ZonedDateTime zonedDateTime = instant. atZone(ZoneId. of( "Asia/Kolkata" ));

How do I get LocalDate from ZonedDateTime?

To convert ZonedDateTime to LocalDate instance, use toLocalDate() method. It returns a LocalDate with the same year, month and day as given date-time. ZonedDateTime zonedDateTime = ZonedDateTime. now(); LocalDate localDate = zonedDateTime.

How do I convert a string to LocalDate?

Parsing String to LocalDateparse() method takes two arguments. The first argument is the string representing the date. And the second optional argument is an instance of DateTimeFormatter specifying any custom pattern. //Default pattern is yyyy-MM-dd LocalDate today = LocalDate.


1 Answers

Java 9+

LocalDate.ofInstant(...) arrived in Java 9.

Instant instant = Instant.parse("2020-01-23T00:00:00Z"); ZoneId zone = ZoneId.of("America/Edmonton"); LocalDate date = LocalDate.ofInstant(instant, zone); 

See code run live at IdeOne.com.

Notice the date is 22nd rather than 23rd as that time zone uses an offset several hours before UTC.

2020-01-22

Java 8

If you are using Java 8, then you could use ZonedDateTime's toLocalDate() method:

yourInstant.atZone(yourZoneId).toLocalDate() 
like image 61
Rob C Avatar answered Sep 30 '22 04:09

Rob C