Reputation: 323
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
Reputation: 86359
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
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