Saturday, January 12, 2013

Convert java.util.Date to xsd:dateTime xml format

When converting java.util.Date to xml xsd dateTime format, one of the approaches is to use XMLGregorianCalendar class to format it to xml xsd format specifications.

input
new java.util.Date()

output
2013-01-12T10:30:09.274-05:00

code snippet:
String convertedDate = "";
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("EST"));
//use below line to pass in a java.util.Date as an argument
//gc.setTime(date);
try {
       convertedDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc).toXMLFormat();
} catch (DatatypeConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

No comments: