如何将ZonedDateTime格式化为yyyy-MM-ddZ

问题描述 投票:0回答:2

我需要将ZonedDateTime转换为XML日期数据类型,格式为yyyy-MM-ddZ。例如:2020-02-14Z。我尝试使用DateTimeFormatter.ofPattern("yyyy-MM-ddZ"),但输出为:2020-02-14+0000。我应该使用哪种DateTimeFormatter模式来获得所需的结果?

java xml datetime-format date-formatting zoneddatetime
2个回答
0
投票

您应该使用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


0
投票

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

如果要在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

© www.soinside.com 2019 - 2024. All rights reserved.