Thursday, February 9, 2012

xsd:date maps to java.util.Calendar

My schema has an element of type xs:date, which jaxb maps to a java.util.Calendar. If I create a Calendar object with Calendar.getInstance(), it marshalls to "2003-11-24-05:00".

How can I get it to marshall to just "2003-11-24"?

SOLUTION:
Write a converter class (see MyConverter below) and added an annotation/appinfo to the xml schema, also shown below.


public class MyConverter
{
    static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    static public String printCalendar(Calendar c)
    {
        return df.format(c.getTime());
    }

    static public Calendar parseCalendar(String c) throws ParseException
    {
        Date d = df.parse(c);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        return cal; 
    }
}

<xsd:schema ...>
<xsd:annotation>
<xsd:appinfo>
<jaxb:globalBindings 
<jaxb:javaType name="java.util.Calendar" xmlType="xsd:date"
printMethod="MyConverter.printCalendar"
parseMethod="MyConverter.parseCalendar"
/>
</jaxb:globalBindings>
</xsd:appinfo>
</xsd:annotation>
...
</xsd:schema>

Source : https://forums.oracle.com/forums/thread.jspa?threadID=1624090

No comments:

Post a Comment