Reputation: 5916
I use JAXB for un/marshaling XML messages which I get from server. Usually I get the XMLGregorianCalendar values in the fields, that are defind as xs:dateTime in the describing XSD files, so the conversion to XMLGregorianCalendar is done automatically by JAXB.
Example from XSD file
<xs:attribute name="readouttime" use="required" type="xs:dateTime" />
However one field is defined as xs:string like this:
<xs:element minOccurs="1" maxOccurs="1" name="Value" type="xs:string" />
but I am receiving a value that should represent the dateTime:
<Value>2014-08-31T15:00:00Z</Value>
Is there any nice way, how to convert this string to XMLGregorianCallendar, or should I use SimpleDateFormat and type the pattern manually? I feel this may be a dangerous part.
Upvotes: 4
Views: 6861
Reputation: 8272
You can use an @XmlJavaTypeAdapter
on your field like this..
@XmlElement(name = "string", required = true)
@XmlJavaTypeAdapter(DateAdapter.class)
protected XMLGregorianCalendar value;
DateAdapter.java
import java.text.SimpleDateFormat;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class DateAdapter extends XmlAdapter<String, XMLGregorianCalendar> {
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public String marshal(XMLGregorianCalendar v) throws Exception {
return dateFormat.format(v);
}
public XMLGregorianCalendar unmarshal(String v) throws Exception {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(v);
}
}
Upvotes: 1
Reputation: 328
My idea
String time = "yourTimeStamp";
SimpleDateFormat f = new SimpleDateFormat("yourFormat");
Date myDate = f.parse(time);
GregorianCalendar c = new GregorianCalendar();
c.setTime(myDate);
XMLGregorianCalendar myDate2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
Upvotes: 2
Reputation: 9342
A quick Google search yields
String mydatetime = "2011-09-29T08:55:00";
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(mydatetime);
Credits go to this blog post.
Upvotes: 5