OffsetDateTime - print offset instead of Z
Asked Answered
P

2

11

I have this code:

String date = "2019-04-22T00:00:00+02:00";

OffsetDateTime odt = OffsetDateTime
      .parse(date, DateTimeFormatter.ISO_OFFSET_DATE_TIME)                             
      .withOffsetSameInstant(ZoneOffset.of("+00:00"));

System.out.println(odt);

This print: 2019-04-21T22:00Z

How can I print 2019-04-21T22:00+00:00? With offset instead of Z.

Proulx answered 20/12, 2019 at 17:46 Comment(1)
docs.oracle.com/javase/8/docs/api/java/time/…Underpinnings
M
15

None of the static DateTimeFormatters do this in the standard library. They either default to Z or GMT.

To achieve +00:00 for no offset, you will have to build your own DateTimeFormatter.

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
        .append(ISO_LOCAL_DATE_TIME) // use the existing formatter for date time
        .appendOffset("+HH:MM", "+00:00") // set 'noOffsetText' to desired '+00:00'
        .toFormatter();

System.out.println(now.format(dateTimeFormatter)); // 2019-12-20T17:58:06.847274+00:00
Monacid answered 20/12, 2019 at 17:59 Comment(0)
S
9

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.

Stimulate answered 21/12, 2019 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.