Default Behaviour
When marshalling a java.util.Date
a JAXB implementation will marshal them if they are not 0
.
Java Model (Root)
import java.util.Date;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlType(propOrder = { "foo", "bar" })
public class Root {
private Date foo;
private Date bar;
public Date getFoo() {
return foo;
}
public void setFoo(Date foo) {
this.foo = foo;
}
public Date getBar() {
return bar;
}
public void setBar(Date bar) {
this.bar = bar;
}
}
Demo
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
root.setFoo(DatatypeConverter.parseDateTime("2013-08-02T11:50:00-04:00").getTime());
root.setBar(DatatypeConverter.parseDateTime("2013-08-02T11:50:00.123-04:00").getTime());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<foo>2013-08-02T11:50:00-04:00</foo>
<bar>2013-08-02T11:50:00.123-04:00</bar>
</root>
Forcing Milliseconds to Be Marshalled with an XmlAdapter
You could create an XmlAdapter
to control the way the java.util.Date
is marshalled out:
Leveraging an XmlAdapter
when Starting from an XML Schema
Below is a link to an answer I gave demonstrating how to leverage an XmlAdapter
when you generate your model from an XML Schema.