OffsetDateTime-打印偏移量,而不是Z

问题描述 投票:1回答:1

我有此代码:

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

java datetime-format
1个回答
2
投票

没有静态DateTimeFormatter在标准库中执行此操作。它们默认为ZGMT

要获得无偏移的+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
© www.soinside.com 2019 - 2024. All rights reserved.