converting Joda time Instant to Java time Instant
Asked Answered
G

3

32

I have an instance of Instant (org.joda.time.Instant) which I get in some api response. I have another instance from (java.time.Instant) which I get from some other call. Now, I want to compare these two object to check which one get the latest one. How would it be possible?

Gumption answered 22/7, 2016 at 17:36 Comment(1)
for comparison you could get the millis from eachHeaves
H
43

getMillis() from joda.time can be compared to toEpochMilli() from java.time.

Class documentation:

Example code.

java.time.Instant myJavaInstant = 
    java.time.Instant.ofEpochMilli( myJodaInstant.getMillis() ) ;

Going the other way.

// Caution: Loss of data if the java.time.Instant has microsecond
// or nanosecond fraction of second.
org.joda.time.Instant myJodaInstant = 
    new org.joda.time.Instant( myJavaInstant.toEpochMilli() ); 
Heaves answered 22/7, 2016 at 17:46 Comment(0)
T
2

You can convert from joda Instant to java's (the datetime and formatting are just an example):

org.joda.time.Instant.parse("10.02.2017 13:45:32", DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss")).toDate().toInstant()

So you call toDate() and toInstant() on your joda Instant.

Tytybald answered 18/4, 2018 at 12:8 Comment(2)
the call to parse makes this answer confusing, but actually calling toDate returns a java.util.Date, which can be used to get the Instant...Uboat
hence the brackets: (the datetime and formatting are just an example)Tytybald
L
-1

I think there is a bug in the Joda-Time sdk. It changes the time and time zone when you convert this way.

My original ISO string is: originalISOString = 2023-08-02T22:00:00.000+01:00

I run the step above as: org.joda.time.Instant.parse(originalISOString, ISODateTimeFormat.dateTime()).toDate().toInstant();

but after running through the step above, my resulting string (using Instant.toString()) is 2023-08-02T21:00:00Z

It has changed the time and the time zone.

Lauder answered 2/8, 2023 at 19:1 Comment(2)
The output is correct. It's not a bug; it's the expected behaviour. An Instant gives you a date-time denoting a moment at UTC (which is specified by a Z).Attribution
So your answer is that there is a bug in Joda-Time SDK? Apparently not, according to the comment to your answer. So how does your answer help anybody who is experiencing this problem? Your answer seems more suitable as a comment - but you can't comment as you don't have enough reputation. Maybe consider deleting this answer?Gastelum

© 2022 - 2024 — McMap. All rights reserved.