参考文章:[url]http://stackoverflow.com/questions/13568543/how-do-you-specify-the-date-format-used-when-jaxb-marshals-xsddatetime[/url]
方法1:instance级别指定,即每次使用时指定
方法2:class级别,即使用Adapter,为一个类的某个属性都使用设置好的日期格式
You can use an XmlAdapter to customize how a date type is written to XML.
Then you use the @XmlJavaTypeAdapter annotation to specify that the XmlAdapter should be used for a specific field/property.
方法1:instance级别指定,即每次使用时指定
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));
}
方法2:class级别,即使用Adapter,为一个类的某个属性都使用设置好的日期格式
You can use an XmlAdapter to customize how a date type is written to XML.
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter<String, Date> {
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public String marshal(Date v) throws Exception {
return dateFormat.format(v);
}
@Override
public Date unmarshal(String v) throws Exception {
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;