How to Convert string to xml gregorian calendar date java

20,247

Solution 1

If you check SimpleDateFormat doc, you will see that there's no T in the format pattern. In order to escape non-pattern characters, wrap them around single quotes ' as shown in this example (taken from the docs):

"hh 'o''clock' a, zzzz" -> 12 o'clock PM, Pacific Daylight Time

I think the proper format should be this:

String format = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
//                         ^-^-----check these
// don't pay attention to the smiley generated above, they're arrows ;)
GregorianCalendar cal = new GregorianCalendar();
     cal.setTime(new SimpleDateFormat(format).parse(sampleDate));
     XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);

Solution 2

This works as well

XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.317-04:00");
GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();
Share:
20,247
Nomad
Author by

Nomad

Updated on July 09, 2022

Comments

  • Nomad
    Nomad almost 2 years

    I am trying to convert String to gregoriancalendar date, it unable to convert. because, the string has different format. like '2015-05-22T16:28:40.317-04:00'. I have seen some of the other examples, but they are not in this time format.

    I am using something like below:

    GregorianCalendar cal = new GregorianCalendar();
             cal.setTime(new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz").parse(sampleDate));
             XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);
    

    I even tried like this too:

    gregory.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(sampleDate));