Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Date to LocalDate when using ThreeTenABP?

NOTE: This is answered already excellently in the JDK world here, but the accepted answer doesn't apply to the Android port of JSR-310 which doesn't have that extended API for Date.

So, what is the best way to convert a java.util.Date to org.threeten.bp.LocalDate?

Date input = new Date();
LocalDate date = ???
like image 743
Alex Florescu Avatar asked Jul 16 '15 11:07

Alex Florescu


People also ask

How do I cast a date in LocalDateTime?

Date date = new Date(); LocalDateTime localDateTime = date. toInstant(). atZone(ZoneId. systemDefault()).

Can we convert LocalDate to date in Java?

Convert LocalDate To Date in Java Step 1: First Create the LocalDate object using either now() or of() method. now() method gets the current date where as of() creates the LocalDate object with the given year, month and day. Step 2: Next, Get the timezone from operating system using ZoneId. systemDefault() method.

What is difference between LocalDate and date?

LocalDate is the date the calendar on the wall says. java. util. Date is not a date, it's an instant, and actually represents a millisecond offset from Unix epoch.


1 Answers

This should do it (inspired by https://stackoverflow.com/a/27378709/286419).

Date dateJavaFormat = new Date();
LocalDate dateThreeTenFormat = Instant.ofEpochMilli(dateJavaFormat.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
like image 58
Alex Florescu Avatar answered Sep 22 '22 16:09

Alex Florescu