georgebp
georgebp

Reputation: 323

How to format ZonedDateTime to yyyy-MM-ddZ

I need to turn ZonedDateTime to XML Date data type, of format yyyy-MM-ddZ. For example: 2020-02-14Z. I try to use DateTimeFormatter.ofPattern("yyyy-MM-ddZ") but the output is: 2020-02-14+0000. Which DateTimeFormatter pattern should I use to get the desired result?

Upvotes: 1

Views: 7242

Answers (2)

Anonymous
Anonymous

Reputation: 86359

DateTimeFormatter.ISO_OFFSET_DATE

Use the built-in 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

If you want a string in UTC with a trailing Z, use ZoneOffset.UTC:

    ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);

2020-02-14Z

If you have got a ZonedDateTime that is not in UTC, convert:

    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

Upvotes: 1

Roman Osadchuk
Roman Osadchuk

Reputation: 1

You should use 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]

Formatted:2020-02-14Z

Upvotes: 0

Related Questions