Getting Wrong Date Using XMLGregorianCalender

670 Views Asked by At

I am trying to get the current date/time to populate in an XML. I am using the code

XMLGregorianCalendar xmlDate = null;
try {
    xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(Calendar.YEAR, Calendar.MONTH+1, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, DatatypeConstants.FIELD_UNDEFINED, TimeZone.LONG).normalize();
    lastUpdatetDateTime.setTextContent(xmlDate.toXMLFormat());
} catch (DatatypeConfigurationException e) {
}

But I get the output as 0001-03-05T10:11:13Z, from all I know, we are in 2017! :)

Even the time is 8 minutes slower. I ran this at 11:21 AM CST.

2

There are 2 best solutions below

0
On BEST ANSWER

Look at the arguments you're passing in to newXMLGregorianCalendar:

[...].newXMLGregorianCalendar(Calendar.YEAR, Calendar.MONTH+1, 
   Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND,
   DatatypeConstants.FIELD_UNDEFINED, TimeZone.LONG).

The Calendar.YEAR, Calendar.MONTH etc values are constants, used to refer to specific parts of a calendar. You'd typically use them like this:

Calendar calendar = ...;
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
// etc

If you want to create an XMLGregorianCalendar for the current date/time, it looks like you need to do that explicitly:

Calendar calendar = new GregorianCalendar();
xmlDate = DatatypeFactory.newInstance().newXMLGregoriantCalendar(
    calendar.get(Calendar.YEAR),
    calendar.get(Calendar.MONTH) + 1,
    // etc
    );

Better, use the java.time classes instead if you possibly can - the java.util.Date and java.util.Calendar classes are really nasty compared with either java.time or its backport.

1
On

When you call newXMLGregorianCalendar() you are expected to provide the year, month, day, etc of the date you want to create.

Your code passed instead the internal constants that designate the various fields, which are going to be small integers totally unrelated to today's date or anything else.

You need to modify that line to provide the actual values for the date/time you want to create. For example:

GregorianCalendar now - new GregorianCalendar();
xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(now);