Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Instant to joda DateTime?

How to convert Instant(java.time.Instant) to joda DateTime (org.joda.time.DateTime)? Or rather, what's the best way to do this?

like image 563
Saif Avatar asked Oct 17 '25 11:10

Saif


1 Answers

tl;dr

new DateTime( myInstant.toEpochMilli() )

java.time replaces Joda-Time

Do you understand that java.time is the successor to Joda-Time? If you have java.time at your disposal, there should be no need to use Joda-Time. The same man, Stephen Colebourne, led both projects, taking lessons learned from Joda-Time to design java.time in JSR 310.

Convert by way of count of milliseconds

But to answer your Question directly: Extract from the Instant object a count of milliseconds since the first moment of 1970 in UTC. Use that count to construct a DateTime object.

Beware of potential data loss. An Instant may contain microseconds or nanoseconds. These will be ignored, of course, when extracting milliseconds.

java.time.Instant myInstant = Instant.now() ; 
long millis = myInstant.toEpochMilli() ;
org.joda.time.DateTime dt = new DateTime( millis ) ;

In java.time, an Instant is always in UTC. To match that on your DateTime, pass the UTC constant to this other constructor.

DateTime dt = new DateTime( millis , DateTimeZone.UTC ) ;
like image 194
Basil Bourque Avatar answered Oct 20 '25 03:10

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!