converting XMLGregorianCalendar object in String format to XMLGregorianCalendar object again

sayan picture sayan · Sep 4, 2014 · Viewed 7.2k times · Source

I have converted an XMLGregorianCalendar object to String using toString() method. So in a String variable I have "2014-09-02T10:55:58.000+05:30" . Now I want to load this value to an XMLGregorianCalendar object again.

   GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(new Date());
        XMLGregorianCalendar xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        System.out.println(xgcal);
        String strDate = xgcal.toString();
        System.out.println("In String format "+strDate);

I want to store this string value to a variable of type XMLGregorianCalendar . I used thsi SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); but cant understand what to do next.Hope I clearly mentioned my problem. Please help me. Thanks in advance.

Answer

T. Büscher picture T. Büscher · Sep 19, 2016

AFAIK you can use:

javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendar(String lexicalRepresentation)

I had a problem similar to the problem the OP describes. I got a XMLGregorianCalendar and had to store it in a String representation. For this purpose I used the .toString() method from XMLGregorianCalendar. Later there was the need to read the stored date and return it as a XMLGregorianCalendar encapsulated in an SOAP-Message.

This example creates a new XMLGregorianCalendar (supposed the stored String is read to hereIsMyString):

XMLGregorianCalendar xmlDate = null;
try {
   xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(hereIsMyString);
    } catch (DatatypeConfigurationException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }