-2

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

Nico
  • 111
  • 10
  • 3
    Welcome to SO. Please read [ask] and properly format your post, e.g. by using a code block, correcting typos (`new Date(...)` instead of `new date(...)` etc.). Also note that you shouldn't be using classes like `Date` which belong to the _old_ date api. Instead, use the `java.time` classes, e.g. `LocalDate`, `ZoneDateTime` etc. – Thomas Aug 24 '22 at 11:53
  • Btw, have a look at the available standard formats for time: what Joda is returning seems to be the ISO time format. – Thomas Aug 24 '22 at 11:56
  • I strongly recommend you don’t use `Date` and `DateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). You may also involve `ZoneOffset.UTC`, `OffsetDateTime` and `DateTimeFormatter`. – Ole V.V. Aug 24 '22 at 17:46

1 Answers1

2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154