【问题标题】:OffsetDateTime - print offset instead of ZOffsetDateTime - 打印偏移量而不是 Z
【发布时间】:2020-04-13 05:07:25
【问题描述】:
我有这个代码:
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
java-time
timezone-offset
【解决方案1】:
在标准库中没有一个静态DateTimeFormatters 这样做。
它们默认为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
【解决方案2】:
我的版本是:
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.of("+00:00") 声明了一个常量,我更喜欢使用它:ZoneOffset.UTC。