I'm using a client library (third party, not mine, cannot change) which utilizes the ThreeTen date types. My project is Java 11 and uses Java 8 date types. What is the recommended way to convert ThreeTeen objects to their Java 8 counterparts?
How can I convert a org.threeten.bp.OffsetDateTime to java.time.OffsetDateTime?
7.3k Views Asked by Fredrik Rambris AtThere are 3 best solutions below
On
It may seem that this need has not been foreseen in the design. No really good and natural option exists for this seemingly simple requirement.
I like to have something to choose from. deHaar has already provided two options that are as good as we can get. So just as a supplement here’s a third one: convert via seconds and nanoseconds since the epoch and total offset seconds.
org.threeten.bp.OffsetDateTime fromThirdParty
= org.threeten.bp.OffsetDateTime.of(2020, 1, 25, 23, 34, 56, 123456789,
org.threeten.bp.ZoneOffset.ofHours(1));
java.time.Instant jtInstant = java.time.Instant
.ofEpochSecond(fromThirdParty.toEpochSecond(), fromThirdParty.getNano());
java.time.ZoneOffset jtOffset = java.time.ZoneOffset.ofTotalSeconds(
fromThirdParty.getOffset().getTotalSeconds());
java.time.OffsetDateTime converted
= java.time.OffsetDateTime.ofInstant(jtInstant, jtOffset);
System.out.println("From " + fromThirdParty);
System.out.println("To " + converted);
Output from this snippet is:
From 2020-01-25T23:34:56.123456789+01:00 To 2020-01-25T23:34:56.123456789+01:00
Possible advantages include: We are transferring 3 numerical fields (vs 7 in deHaar’s first conversion), thus reducing the risk of transferring a wrong value by error. And we still avoid formatting into a string and parsing back (which feels like a waste to me but is nice and short).
And please wrap it into a method with a nice name like deHaar has done.
On
Actually conversion is simple using parse. I was looking for a solution and landed on this thread. Upon inspection I figured there is an easy way so posted here.
java.time.OffsetDateTime odt = java.time.OffsetDateTime.now();
org.threeten.bp.OffsetDateTime ODT = org.threeten.bp.OffsetDateTime.parse(odt.toString());
Similarly to convert vice versa
org.threeten.bp.OffsetDateTime ODT = org.threeten.bp.OffsetDateTime.now();
java.time.OffsetDateTime odt = java.time.OffsetDateTime.parse(ODT.toString());
There seems to be no built-in way to convert one instance to the other.
I think you have write your own converters, like one of the following:
Part-by-part conversion:
Parsing the formatted output of the other instance:
Haven't tested which one is more efficient...