[英]How to format ZonedDateTime to yyyy-MM-ddZ
I need to turn ZonedDateTime to XML Date data type, of format yyyy-MM-ddZ
.我需要将 ZonedDateTime 转换为 XML 日期数据类型,格式为yyyy-MM-ddZ
。 For example: 2020-02-14Z
.例如: 2020-02-14Z
。 I try to use DateTimeFormatter.ofPattern("yyyy-MM-ddZ")
but the output is: 2020-02-14+0000
.我尝试使用DateTimeFormatter.ofPattern("yyyy-MM-ddZ")
但输出是: 2020-02-14+0000
。 Which DateTimeFormatter pattern should I use to get the desired result?我应该使用哪种 DateTimeFormatter 模式来获得所需的结果?
Use the built-in 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);
When I ran this snippet just now, the output was:当我刚刚运行这个片段时,输出是:
2020-02-14-03:00 2020-02-14-03:00
If you want a string in UTC with a trailing Z
, use ZoneOffset.UTC
:如果你想要一个带有尾随Z
UTC 字符串,请使用ZoneOffset.UTC
:
ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);
2020-02-14Z 2020-02-14Z
If you have got a ZonedDateTime
that is not in UTC, convert:如果您有一个不在 UTC 中的ZonedDateTime
,请转换:
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 2020-02-14Z
You should use DateTimeFormatter.ofPattern("yyyy-MM-dd'Z'").您应该使用 DateTimeFormatter.ofPattern("yyyy-MM-dd'Z'")。 Here is what i got:这是我得到的:
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));
Not formatted:2020-02-14T00:00-05:00[EST5EDT]未格式化:2020-02-14T00:00-05:00[EST5EDT]
Formatted:2020-02-14Z格式:2020-02-14Z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.