Search code examples
androidthreetenbp

Convert Java.util.Calendar to org.threeten.bp.LocalDateTime (for Android)


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!


Solution

  • Your solution is less than optimal.

    LocalDateTime has no zone/offset

    Firstly, 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:

    • We do not know the zone.
    • We intend multiple zones for a non-simultaneous moment (“all our factories around the world close at noon for lunch”).
    • We are scheduling out into the future more that a few weeks and so we get might get hit by capricious politicians re-defining the time zone such as Daylight Saving Time (DST) with little notice. We use LocalDateTime for logic, and present to the user as a ZonedDateTime when generating a transient calendar.

    DateTimeUtils for conversions

    Next, 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.