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.
LocalDateTimehas no zone/offsetFirstly, your use of
LocalDateTimeis inappropriate almost certainly. You are discarding valuable information about time zone or offset. TheLocalDateTimeclass 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, andZonedDateTimewhen dealing with actual moments on the timeline.We only use
LocalDateTimewhen:LocalDateTimefor logic, and present to the user as aZonedDateTimewhen generating a transient calendar.DateTimeUtilsfor conversionsNext, your conversion math is needless.
The
DateTimeUtilsclass provides utility methods for conversions.or…
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.