问题
While working with legacy code not yet updated for the modern java.time classes, I need to convert a ZonedDateTime to XMLGregorianCalendar. So I thought I'd go by way of GregorianCalendar, calling GregorianCalendar.from( ZonedDateTime ).
I see methods for going from XMLGregorianCalendar
to GregorianCalendar
: XMLGregorianCalendar::toGregorianCalendar.
➥ I need the opposite, going from GregorianCalendar
to XMLGregorianCalendar
.
回答1:
DatatypeFactory.newInstance().newXMLGregorianCalendar( … )
While neither the XMLGregorianCalendar
nor GregorianCalendar
classes offer the conversion method you need, there is a workaround.
A javax.xml.datatype.DatatypeFactory object can convert from GregorianCalendar
to XMLGregorianCalendar
by calling its newXMLGregorianCalendar method.
XMLGregorianCalendar xmlGregCal =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gregCal )
;
To complete the entire cascade you mentioned, from java.time.ZonedDateTime
to GregorianCalendar
to XMLGregorianCalendar
.
XMLGregorianCalendar xmlGregCal =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar(
GregorianCalendar
.from(
myZonedDateTime
)
)
;
来源:https://stackoverflow.com/questions/59257517/convert-gregoriancalendar-to-xmlgregoriancalendar