fmt:formatDate shows month too much

Im trying to show a date in my JSP page, with use of the fmt:formatDate tag.

So in my JSP im doing this:

<td><fmt:formatDate pattern="dd-MM-yyyy" value="${document.documentDate}" /></td>

The document.documentDate is a value that I get from an XMLGregorianCalendar, that I obviously parse.

public Date getDocumentDate() {
    return convertDateFromXMLDate(documentDate);
}

protected Date convertDateFromXMLDate(XMLGregorianCalendar date) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, date.getYear());
    cal.set(Calendar.MONTH, date.getMonth());
    cal.set(Calendar.DAY_OF_MONTH, date.getDay());
    cal.set(Calendar.HOUR, date.getHour());
    cal.set(Calendar.MINUTE, date.getMinute());
    cal.set(Calendar.SECOND, date.getSecond());
    return cal.getTime();

}

The XMLGregorianCalendar values are correct. the cal.getTime() is also correct. (I debugged the cal.getTime.getMonth() value.

Although my JSP shows one month too much! Instead of 1-1-2014 it shows 1-2-2014 (dd-MM-yyyy)

Any thoughts?

Jon Skeet
people
quotationmark

This is the problem:

cal.set(Calendar.MONTH, date.getMonth());

XMLGregorianCalendar uses a month range of 1-12. java.util.Calendar uses a month range of 0-11. You want:

cal.set(Calendar.MONTH, date.getMonth() - 1);

Also note that you might want to use new GregorianCalendar() rather than Calendar.getInstance() in order to avoid the possibility of it not being a Gregorian calendar... and you should also consider whether you really want it in the system default time zone. (Maybe you do, maybe you don't. If this is code running on the server, I suggest you don't - why should the location of the server change the results?)

people

See more on this question at Stackoverflow