How to convert from Android Java Date and Calendar to threeten LocalDateTime
Calendar calTime = Calendar.getInstance();
Date date = calTime.getTime();
LocalDateTime ldt = Instant.ofEpochSecond(date.getTime()/1000)
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
Fixed!
Your solution is less than optimal.
LocalDateTime
has no zone/offsetFirstly, your use of LocalDateTime
is inappropriate almost certainly. You are discarding valuable information about time zone or offset. The LocalDateTime
class purposely has no concept of time zone or offset-from-UTC, and therefore does not represent an actual moment, only a rough idea about possible moments over a range of 26-27 hours or so.
Instead use Instant
, OffsetDateTime
, and ZonedDateTime
when dealing with actual moments on the timeline.
We only use LocalDateTime
when:
LocalDateTime
for logic, and present to the user as a ZonedDateTime
when generating a transient calendar.DateTimeUtils
for conversionsNext, your conversion math is needless.
The DateTimeUtils
class provides utility methods for conversions.
ZonedDateTime zdt = DateTimeUtils.toZonedDateTime( myCalendar ) ;
or…
Instant instant = DateTimeUtils.toInstant( myCalendar ) ;
P.S. Do not answer your Question inside the body text of the Question. Instead, post an actual Answer, and then accept it to close the Question.
Tips: For those wanting to use ThreeTen-Backport in Android, see the ThreeTenABP project. And see How to use ThreeTenABP in Android Project.