我需要将ZonedDateTime转换为XML日期数据类型,格式为yyyy-MM-ddZ
。例如:2020-02-14Z
。我尝试使用DateTimeFormatter.ofPattern("yyyy-MM-ddZ")
,但输出为:2020-02-14+0000
。我应该使用哪种DateTimeFormatter模式来获得所需的结果?
您应该使用DateTimeFormatter.ofPattern(“ yyyy-MM-dd'Z'”)。这是我得到的:
LocalDate localDate = LocalDate.now();
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.of("EST5EDT"));
System.out.println("Not formatted:" + zonedDateTime);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'Z'");
System.out.println("Formatted:" + formatter.format(zonedDateTime));
未格式化:2020-02-14T00:00-05:00 [EST5EDT]
Formatted:2020-02-14Z
使用内置的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
如果要在UTC中以Z
结尾的字符串,请使用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