OffsetDateTime - 打印偏移量而不是 Z

9

我有这样的代码:

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);

这打印出来的是:2019-04-21T22:00Z

如何打印 2019-04-21T22:00+00:00?使用偏移量而不是 Z


2
https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#format-java.time.format.DateTimeFormatter- - JB Nizet
2个回答

12

标准库中的静态DateTimeFormatter都没有这样的功能。 它们要么默认为Z,要么默认为GMT

要实现不带偏移量的+00:00,你需要构建自己的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

7

我的版本将会是:

    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));

输出结果如下所示:

2019-04-21T22:00:00+00:00

toString() 方法输出的格式不符合要求时,可以使用 DateTimeFormatter 将其格式化为所需的格式。在格式模式字符串中,小写的 xxx 会产生带有冒号的小时和分钟格式的偏移量,即使偏移量为0也是如此。

虽然 OffsetDateTime.toString() 不会产生您想要的格式,但 OffsetDateTime 仍然能够解析它而无需任何显式格式化。因此,在我的代码版本中,我将其省略了。

已经声明了一个常量 ZoneOffset.UTC,表示 ZoneOffset.of("+00:00"),我更喜欢使用这个常量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接