Simple conversion between java.util.Date and XMLGregorianCalendar

后端 未结 7 1316
夕颜
夕颜 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:03

    Customizing the Calendar and Date while Marshaling

    Step 1 : Prepare jaxb binding xml for custom properties, In this case i prepared for date and calendar

    
    
    
    
    
    


    Setp 2 : Add custom jaxb binding file to Apache or any related plugins at xsd option like mentioned below

    
      ${project.basedir}/src/main/resources/tutorial/xsd/yourxsdfile.xsd
      com.tutorial.xml.packagename
      ${project.basedir}/src/main/resources/xsd/jaxbbindings.xml
    
    

    Setp 3 : write the code for CalendarConverter class

    package com.stech.jaxb.util;
    
    import java.text.SimpleDateFormat;
    
    /**
     * To convert the calendar to JaxB customer format.
     * 
     */
    
    public final class CalendarTypeConverter {
    
        /**
         * Calendar to custom format print to XML.
         * 
         * @param val
         * @return
         */
        public static String printCalendar(java.util.Calendar val) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
            return simpleDateFormat.format(val.getTime());
        }
    
        /**
         * Date to custom format print to XML.
         * 
         * @param val
         * @return
         */
        public static String printDate(java.util.Date val) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return simpleDateFormat.format(val);
        }
    }
    

    Setp 4 : Output

      
       2014-09-25T07:23:05 Calendar class formatted
    
       2014-09-25 - Date class formatted
    
    

提交回复
热议问题