OffsetDateTime - print offset instead of Z

南笙酒味 提交于 2020-12-10 04:07:58

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/59429419/offsetdatetime-print-offset-instead-of-z

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!