How to convert java.time.ZonedDateTime to XMLGregorianCalendar?
Asked Answered
B

1

21

Is there any short way to convert java.time.ZonedDateTime to XMLGregorianCalendar?

Maybe I need some intermediate steps like convert ZonedDateTime to java.util.Date, but that will make code too messy.

The problem appeared in JAX-WS web services, datetime there is passed as XMLGregorianCalendar.

Boarder answered 23/4, 2014 at 8:18 Comment(1)
Show some code how you are doing it. I had that issue but to convert from XMLGregorianCalendar to a normal date without the timezone just simple yyyy-MM-dd date. Due to the fact that Java JAX-WS maps dates to XMLGregorianCalendar instead of Date even if you defined that as such in your WSDL data types.Windjammer
B
42

At the current moment I think it's the most straightforward way to do it:

ZonedDateTime now = ZonedDateTime.now();
GregorianCalendar gregorianCalendar = GregorianCalendar.from(now); 
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
Boarder answered 23/4, 2014 at 9:46 Comment(1)
To other readers: Be aware of the time zone involved here. When the optional ZoneId argument is omitted from ZonedDateTime.now, the JVM’s current default time zone is implicitly assigned. I recommend instead always specifying explicitly your desired/expected time zone. Example: ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ). The rest of the Answer here is spot-on correct.Quacksalver

© 2022 - 2024 — McMap. All rights reserved.