0

OffsetDateTime does not correctly parse the time when a defined time is sent to me

I have a service with a timezone UTC +4:00

I am sent two possible cases in STRING:

1- 2022-03-30T11:22:33.44+04:00 
2- 2022-03-30T11:22:33.44+0400

but when I do a

DateTimeFormatter formatter = DateTimeFormatter
        .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS[xxx][xx][X]");

OffsetDateTime.parse("2022-03-30T11:22:33.44+04:00", formatter);

always returns me 2022-03-30T11:22:33.440

This is technically incorrect because my servers are in the same zone, so it should be: 2022-03-30T07:22:22:33.44Z

but whatever parse I do it doesn't work, is there any way to do it this way?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
AntoCode
  • 395
  • 5
  • 18
  • From your code I am getting `java.time.format.DateTimeParseException: Text '2022-03-30T11:22:33.44+04:00' could not be parsed at index 20`. – Ole V.V. Mar 31 '22 at 17:50
  • *always returns me **2022-03-30T11:22:33.440*** Are you saying it returns an `OffsatDateTime` without offset??!! That sounds extremely strange. – Ole V.V. Mar 31 '22 at 17:51
  • That is my doubt, it returns without the offset and but it does not apply it, I should remove those hours +04:00 and apply it to the code. – AntoCode Mar 31 '22 at 17:57
  • This works for me: (1) Defining `formatter` as `new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE_TIME).appendPattern("[xxx][xx][X]").toFormatter()`. (2) Parsing this way: `OffsetDateTime.parse(input, formatter).withOffsetSameLocal(ZoneOffset.UTC)`. From both your input strings I get `2022-03-30T11:22:33.440Z`. – Ole V.V. Mar 31 '22 at 18:09
  • Hi @OleV.V. At that point I've arrived too, but the thing is that where my jar is hosted the JVM has UTC +04:00 if it is sent 2022-03-30T11:22:33.44+04:00 being in the same zone it should calculate correctly that timezone and disconnect the 4h that are sent to the string that is to say: 2022-03-30T07:22:22:33.44Z – AntoCode Mar 31 '22 at 18:18
  • *so it should be: **2022-03-30T07:22:22:33.44Z*** Not according to the docs. It should preserve the offset from the string, so `+04:00`. – Ole V.V. Mar 31 '22 at 18:19
  • To use the JVM’s default time zone regardless of what is in the string, parse like `OffsetDateTime.parse(input, formatter).atZoneSimilarLocal(ZoneId.systemDefault()).toOffsetDateTime()`. – Ole V.V. Mar 31 '22 at 18:20
  • Correct, and when I debug it is taking the zone correctly, but it does not take away the 4 hours, it is still 11:22.... instead of 07:22. I can not find a parse correctly, because it removes the +04:00 but does not apply it to the date only removes that string. – AntoCode Mar 31 '22 at 18:29
  • Ah, that’s what you wanted? Use `atZoneSameInstant()`. So `OffsetDateTime.parse(input, formatter).atZoneSameInstant(ZoneId.systemDefault()).toOffsetDateTime()` – Ole V.V. Mar 31 '22 at 18:31

0 Answers0