My version would be:
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxxx");
String date = "2019-04-22T00:00:00+02:00";
OffsetDateTime odt = OffsetDateTime
.parse(date)
.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odt.format(outputFormatter));
Output is the desired:
2019-04-21T22:00:00+00:00
When toString()
gives output in an unwanted format, the answer is using a DateTimeFormatter
for formatting into the desired format. Lowercase xxx
in the format pattern string produces offset formatted in hours and minutes with a colon as shown, also when the offset is 0.
While OffsetDateTime.toString()
doesn’t produce the format that you wanted, OffsetDateTime
is still able to parse it without any explicit formatter. So in my version of the code I left it out.
There is a constant already declared for ZoneOffset.of("+00:00")
, which I prefer to use: ZoneOffset.UTC
.