Our software architect made decision to remove Joda time library from our project dependencies and to use features of Java 8 time. I am doing research of our project and I am trying to find all places where we are using Joda time lib and determine what actually we are using (joda LocalDate
, DateTime
, etc.).
I am not an expert of Joda time library and I not an expert of Java 8 time, so I have some questions:
In code I saw a lot of places like this:
DateTime jodaDateTime = new DateTime();
doSomething(jodaDateTime.toDate());
I am a little bit confused.
(Q1) Does it make any sense to use joda
DateTime
in this particular case? I believe, that we can use just classic java.util.Date
and we do not need Joda:
java.util.Date date = new Date();
doSomething(date);
Correct?
Also, I saw this piece of code:
org.joda.time.DateTime jodaDateTime = new DateTime();
org.joda.time.DateTime jodaDateTimeInPast = jodaDateTime.minusSeconds(60);
doSomething(jodaDateTimeInPast.toDate());
I think, that java 8 time API provides the great support for calculating any dates in the past, so I have idea how to replace the piece of code above to Java 8:
LocalDatetime java8DateTime = LocalDateTime.now();
LocaldateTime java8DateTimeInPast = java8DateTime.minusSeconds(60);
Date java8Date = Date.from(java8DateTimeInPast.atZone(ZoneId.systemDefault()).toInstant());
doSomething(java8Date);
(Q2) Have I done it in the right way? I am not sure on 100%.
I just found this link with a table: "Converting from Joda-Time to java.time"
There are I found info, that I need to use java.time.ZonedDateTime
or java.time.OffsetDateTime
classes, but not java.time.LocalDateTime
, because LocalDateTime
-
Same concept - date and time without time-zone
Please confirm that my refactoring is correct (for Q1 and Q2).
Most questions about conversion should be handled by my blog on the topic.
Q1a:
There is no point in creating a Joda-Time object only to change back to java.util.Date
. However, the method should probbaly take Instant
or ZonedDateTime
:
Instant instant = Instant.now();
doSomething(instant); // method changed to take Instant
Note that Instant
is the closest match to java.util.Date
.
Q1b:
This case involves a time-zone, so should use ZonedDateTime
.
ZonedDateTime java8DateTime = ZonedDateTime.now(); // uses ZoneId.systemDefault()
ZonedDateTime java8DateTimeInPast = java8DateTime.minusSeconds(60);
doSomething(java8DateTimeInPast.toInstant());
Again, this assumes that doSomething
is changed to take an Instant
.
The key to using java.time
properly is to think about what data type is correct for each piece of data.
LocalDate
LocalTime
ZonedDateTime
Instant
OffsetDateTime
.