XMLGregorianCalendar not displayed in the right format when marshalled

2.5k views Asked by At

I'm getting some dates from the database, putting them into objects of classes derived from an XSD schema using JAXB and then marshalling the objects to an XML file.

One of the derived classes has an XMLGregorianCalendar field, and I want the date that I put there to be written into the XML file in the "yyyy-MM-dd'T'HH:mm:ss" format.

Following the instructions from the answers to this question does not solve my problem. This is what I'm doing:

String formattedDate = sdf.format(dateFromTheDatabase);
        gc1 = convertStringToXmlGregorian(formattedDate);
        gc1.setTimezone(60);
components.setDate(gc1);

The function that I'm using (more or less copied from an answer to the above linked question):

public XMLGregorianCalendar convertStringToXmlGregorian(String dateString)     throws DatatypeConfigurationException
{
    try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
            java.util.Date date = sdf.parse(dateString);
            GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
            gc.setTime(date);
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        } 
}

The date that I get in my XML when I marshal the objects I filled:

2015-06-03+01:00

...whereas I want my date to be in this format:

2015-06-03T00:00:00

Things I also tried:

  • replacing
    "yyyy-MM-dd HH:mm:ss"
    with
    "yyyy-MM-dd'T'HH:mm:ss"

  • replacing

        DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);    
    

    with

        DatatypeFactory.newInstance().newXMLGregorianCalendar(
        gc.get(Calendar.YEAR), gc.get(Calendar.MONTH) + 1, gc.get(Calendar.DAY_OF_MONTH),
        gc.get(Calendar.HOUR_OF_DAY), 0,0,0,60);
    
1

There are 1 answers

0
Meno Hochschild On BEST ANSWER

Okay, now my comment as answer:

Somewhere in JAXB (you have not yet shown your relevant Java file) you need to set the right data type using the annotation @XmlSchemaType(name="dateTime"). Probably you only have set "date" instead of "dateTime" so the time part of your XMLGregorianCalendar-object has been suppressed by JAXB-layer.

Another advise:

What you have presented so far seems in part to be double work - with regards to the usage of SimpleDateFormat. If your input is already an object of type java.util.Date then you don't need to format and parse it again. Just pass it as argument to a GregorianCalendar.setTime()-method.