Date time conversion in Java8

89 views Asked by At

I tried searching across the web, but unable to find a suitable answer and hence posting here. I am calling another API which gives me the date-time like "2022-02-05T17:13:20-06:00[America/Chicago]" I would like to convert this to a format like "2022-02-05T17:13:20.000Z" (I am unsure what the milli-second will turn out as) Could someone help me achieve this? I am unable to get any example for this specific conversion scenario!!!

Regards, Sriram

2

There are 2 answers

1
Ram On

Here below is a code snippet that I was able to generate.... But, I am unsure of that is correct. Please let me know if you feel anything is incorrect.

String requestTime = "2022-02-05T17:13:20-06:00[America/Chicago]";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX'['VV']'");
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(requestTime, formatter);
        zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"));
        System.out.println(zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")));
0
Roland Kreuzer On

For the sample values given getting to a UTC timestamp should be something like

ZonedDateTime.parse("2022-02-05T17:13:20-06:00[America/Chicago]").toInstant().toString()

The datetime value including the timezone is the canonical representation of a ZonedDateTime and therefore can be parsed as such.

Instant is a UTC timestamp that prints in the form of 2022-02-05T23:13:20Z

You could take more influence on the behavior using a DateTimeFormatter - but since both input and output seem to be standard formats it does not seem necessary.