1

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?

georgebp
  • 193
  • 3
  • 17
  • Do you want a literal Z or a Z representing the "zulu" (UTC) time zone? – Freiheit Feb 14 '20 at 18:09
  • Use `z` (lowercase) if you want the time-zone name. The `Z` represents the zone-offset –  Feb 14 '20 at 18:34
  • 1
    @Freiheit the Z representing zulu time zone, if that's the time zone the user is in. I don't want to hardcode the Z, I want the time zone format that uses Z to represent UTC. – georgebp Feb 14 '20 at 18:38
  • Reviewing this answer - https://stackoverflow.com/questions/8405087/what-is-this-date-format-2011-08-12t201746-384z . I think you want ISO-8601 formatted time zones but only the date component and not the time component. According to https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html I think you then want to use `X` as your zone designator see "ISO 8601 Time zone" – Freiheit Feb 14 '20 at 18:47

2 Answers2

1

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

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