Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 554
Naresh Avatar asked Oct 09 '15 04:10

Naresh


People also ask

What is the replacement of Joda time?

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.

Is Joda time included in Java 8?

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.

How do I parse LocalDateTime to ZonedDateTime?

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.


1 Answers

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.

like image 141
Andreas Avatar answered Nov 02 '22 06:11

Andreas