Simple conversion between java.util.Date and XMLGregorianCalendar

后端 未结 7 1333
夕颜
夕颜 2020-12-02 04:25

I\'m looking for a simple method of converting between java.util.Date and javax.xml.datatype.XMLGregorianCalendar in both directions.

Here is the code that

7条回答
  •  孤街浪徒
    2020-12-02 05:25

    I had to make some changes to make it work, as some things seem to have changed in the meantime:

    • xjc would complain that my adapter does not extend XmlAdapter
    • some bizarre and unneeded imports were drawn in (org.w3._2001.xmlschema)
    • the parsing methods must not be static when extending the XmlAdapter, obviously

    Here's a working example, hope this helps (I'm using JodaTime but in this case SimpleDate would be sufficient):

    import java.util.Date;
    import javax.xml.bind.DatatypeConverter;
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    import org.joda.time.DateTime;
    
    public class DateAdapter extends XmlAdapter {
        @Override
        public Object marshal(Object dt) throws Exception {
            return new DateTime((Date) dt).toString("YYYY-MM-dd");
        }
    
        @Override
            public Object unmarshal(Object s) throws Exception {
            return DatatypeConverter.parseDate((String) s).getTime();
        }
    }
    

    In the xsd, I have followed the excellent references given above, so I have included this xml annotation:

    
        
            
        
        
            
        
    
    

提交回复
热议问题