-1

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ram
  • 327
  • 1
  • 4
  • 18

2 Answers2

2

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.

Roland Kreuzer
  • 912
  • 4
  • 11
0

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'")));
Ram
  • 327
  • 1
  • 4
  • 18
  • 1
    No, it’s not correct. The trailing `Z` in your result means UTC, so you need to convert from the UTC offset in the string (`-06:00`) to UTC. Drop the first formatter and just parse the string through `ZonedDateTime.parse(requestTime)` since it is in the default format for a `ZonedDateTime`. To convert and format use `String output = zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX"));`. Output will be `2022-02-05T23:13:20.000Z`, which is the correct UTC equivalent to your input. – Ole V.V. Aug 31 '22 at 18:08