我需要将 ZonedDateTime 转换为 XML 日期数据类型,格式为 yyyy-MM-ddZ
。例如:2020-02-14Z
。我尝试使用 DateTimeFormatter.ofPattern("yyyy-MM-ddZ")
但输出是:2020-02-14+0000
。我应该使用哪种 DateTimeFormatter 模式来获得所需的结果?
最佳答案
DateTimeFormatter.ISO_OFFSET_DATE
使用内置的DateTimeFormatter.ISO_OFFSET_DATE
。
ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Fortaleza"));
String dateForXml = dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE);
System.out.println(dateForXml);
当我刚才运行这个代码片段时,输出是:
2020-02-14-03:00
如果您想要一个带有 Z
的 UTC 字符串,请使用 ZoneOffset.UTC
:
ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);
2020-02-14Z
如果您的 ZonedDateTime
不是 UTC,请转换:
ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Fortaleza"));
OffsetDateTime odt = dateTime.toOffsetDateTime()
.withOffsetSameInstant(ZoneOffset.UTC);
String dateForXml = odt.format(DateTimeFormatter.ISO_OFFSET_DATE);
2020-02-14Z
关于java - 如何将 ZonedDateTime 格式设置为 yyyy-MM-ddZ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60231416/