Home > Net >  How to convert Instant to joda DateTime?
How to convert Instant to joda DateTime?

Time:02-10

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

CodePudding user response:

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 ) ;
  •  Tags:  
  • Related