Converting from Joda to Java time

404 Views Asked by At

I need to convert joda time to Java time but having some issues

My joda time code : p.s method is a long type (long argDateString)

DateTime istime = new DateTime(argDateString*1000);

DateTime NormalTime = istime.withZone(DateTimeZone.forID("UTC"));

return normalTime.toString();

My Java code :

Date istime = new date(argDateString*1000);

DateFormat normalTime =  DateFormat.getDateTimeInstance(DateFormat.Full, DateFormat.Full);

Return normalTime.format(istime);

With Joda I was getting

1970-01-15T05:45:05.000Z 

With Java I am getting

15 January 1970 05:45:05 o'clock UTC

So is there a way to get what i was getting with Joda time ?

Thanks

1

There are 1 best solutions below

0
On

tl;dr

java.time.Instant
.ofEpochSecond(
    Long.parseLong( input )
)
.toString()

Details

Never use Date and DateFormat classes. These are terribly flawed, and are now legacy. They were supplanted by the modern java.time classes defined in JSR 310. The java.time framework is the official successor to the Joda-Time project, both being led by the same man, Stephen Colebourne.

Your first bit of code makes no sense: argDateString*1000. Strings cannot be multiplied.

I suspect your text holds a number of seconds since the first moment of 1970 as seen in UTC. If so, use Long class to parse to a long primitive.

long seconds = Long.parseLong( input ) ;  // Parse text into a number. 

Pass that number to a static factory method for Instant.

Instant instant = Instant.ofEpochSecond( seconds ) ;

Now you have an object whose value represents a moment, a point on the timeline, as seen in UTC.

To generate text in your desired standard ISO 8601 format, merely call toString. The java.time classes use the ISO 8601 formats by default when generating/parsing text.

String output = instant.toString() ;

All this has been covered many times on Stack Overflow. Search to learn more.