How do you specify the date format used when JAXB marshals xsd:dateTime?

Solution 1:

You can use an XmlAdapter to customize how a date type is written to XML.

package com.example;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<String, Date> {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String marshal(Date v) throws Exception {
        synchronized (dateFormat) {
            return dateFormat.format(v);
        }
    }

    @Override
    public Date unmarshal(String v) throws Exception {
        synchronized (dateFormat) {
            return dateFormat.parse(v);
        }
    }

}

Then you use the @XmlJavaTypeAdapter annotation to specify that the XmlAdapter should be used for a specific field/property.

@XmlElement(name = "timestamp", required = true) 
@XmlJavaTypeAdapter(DateAdapter.class)
protected Date timestamp; 

Using a xjb binding file:

<xjc:javaType name="java.util.Date" xmlType="xs:dateTime"
        adapter="com.example.DateAdapter"/>

will produce the above mentioned annotation.
(By eventually adding the xjc namespace: xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc")

Solution 2:

I use a SimpleDateFormat to create the XMLGregorianCalendar, such as in this example:

public static XMLGregorianCalendar getXmlDate(Date date) throws DatatypeConfigurationException {
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd").format(date));
}

public static XMLGregorianCalendar getXmlDateTime(Date date) throws DatatypeConfigurationException {
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date));
}

The first method creates an instance of XMLGregorianCalendar that is formatted by the XML marshaller as a valid xsd:date, the second method results in a valid xsd:dateTime.