Convert GregorianCalendar to XMLGregorianCalendar

给你一囗甜甜゛ 提交于 2020-01-16 08:08:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!