Easy way to convert Java 8's LocalDateTime to Joda's LocalDateTime

32,855

Solution 1

Convert through epoch millis (essentially a java.util.Date()):

java.time.LocalDateTime java8LocalDateTime = java.time.LocalDateTime.now();

// Separate steps, showing intermediate types
java.time.ZonedDateTime java8ZonedDateTime = java8LocalDateTime.atZone(ZoneId.systemDefault());
java.time.Instant java8Instant = java8ZonedDateTime.toInstant();
long millis = java8Instant.toEpochMilli();
org.joda.time.LocalDateTime jodaLocalDateTime = new org.joda.time.LocalDateTime(millis);

// Chained
org.joda.time.LocalDateTime jodaLocalDateTime =
        new org.joda.time.LocalDateTime(
            java8LocalDateTime.atZone(ZoneId.systemDefault())
                              .toInstant()
                              .toEpochMilli()
        );

// One-liner
org.joda.time.LocalDateTime jodaLocalDateTime = new org.joda.time.LocalDateTime(java8LocalDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());

Single line, but long, so "easy"? It's all relative.

Solution 2

Both localDate types consist of (year, month, date), so just copy those values:

public static org.joda.time.LocalDate toJoda(java.time.LocalDate input) {
    return new org.joda.time.LocalDate(input.getYear(),
                                       input.getMonthValue(),
                                       input.getDayOfMonth());
}
Share:
32,855
Naresh
Author by

Naresh

Updated on July 09, 2022

Comments

  • Naresh
    Naresh almost 2 years

    Is there any easy way to convert Java 8's LocalDateTime to Joda's LocalDateTime?

    One of the ways is to convert it to String and then create Joda's LocalDateTime from that String.