Search code examples
javadatejava.util.date

Invalid value 0 for Month field. while converting util.date to XMLgregoriandate?


I am converting java.util.Date to XMLGregorianDate.

When I print My util date on console, it displays:

Date: 2011-01-25 20:33:46.54

But after conversion, when I try to use it, gives me following exception: org.springframework.ws.soap.client.SoapFaultClientException: Invalid value 0 for Month field.

Code for Date conversion is:
 DatatypeFactory df = null;

                    try {
                        df = DatatypeFactory.newInstance();
                    } catch (DatatypeConfigurationException e) {
                        e.printStackTrace();
                    }

            GregorianCalendar gc = new GregorianCalendar();
            gc.setTimeInMillis(account.getCreationDate().getTime());

method returns: df.newXMLGregorianCalendar(gc);

Also Interesting thing is that, when I display util Date.getYear() and getMonth() methods (deprecated method used just to display date on console), output on console was:

Year: 111 Month: 0

Why this is happening? Can anyone tell reason behind this? Thank you in advance.


Solution

  • Well, printing out date.getYear() and date.getMonth() should indeed print 111 and 0, as getYear() returns the number of years since 1900, and getMonth() returns a 0-based month. A crazy API for sure, but that's the way it's documented.

    Your conversion code isn't really clear though - you never use df, so what's the point of it? Likewise, I can't see any mention of XMLGregorianDate in your code... could you give a short but complete program which demonstrates the problem? Something that we can build and run?

    As a side issue, in general I would heartily recommend using Joda Time instead of java.util.{Date,Calendar} where possible. It may not help in this particular situation, but it avoids a lot of the poor design decisions of the built-in classes, and allows you to express exactly what you mean better (local dates, local times etc).