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.
Correct Option: D. In java 8,we are asked to migrate to java. time (JSR-310) which is a core part of the JDK which replaces joda library project.
Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.
Convert LocalDateTime to ZonedDateTime The LocalDateTime has no time zone; to convert the LocalDateTime to ZonedDateTime , we can use . atZone(ZoneId. systemDefault()) to create a ZonedDateTime containing the system default time zone and convert it to another time zone using a predefined zone id or offset.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With