我有这个代码:
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
.
标准库中没有静态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
我的版本是:
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
。