Xs: String in xs: DateTime format for XMLGregorianCalendar

I use JAXB for un / marshaling the XML messages that I receive from the server. I usually get XMLGregorianCalendar values ​​in fields that are divided as xs: dateTime in the description of the 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 get a value that should represent dateTime:

<Value>2014-08-31T15:00:00Z</Value>

Is there any good way how to convert this string to XMLGregorianCallendar, or should I use SimpleDateFormat and type the template manually? I feel this can be a dangerous part.

+4
source share
3

Google

String mydatetime = "2011-09-29T08:55:00";
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(mydatetime);

.

+5

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);
+2

You can use @XmlJavaTypeAdapterin 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);
    }

}
+1
source

All Articles