Search code examples
javaxmlcalendarxmlgregoriancalendar

Getting Wrong Date Using XMLGregorianCalender


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.


Solution

  • 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.