tags:

views:

143

answers:

1

Hi,

I'm not quite sure what field to use when adding more than 30 days to a Java Calendar object. Is there any difference in between Calendar.DAY_OF_MONTH and Calendar.DAY_OF_YEAR?

Example:

GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.DAY_OF_YEAR, 90);

vs

GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.DAY_OF_MONTH, 90);

Thanks.

+3  A: 

I don't think it makes a difference when you call add. The distinction is important when you call the getters.

Both methods work fine, right? For more than 30 days, as well as negative amounts.

The (admittedly complicated) source for GregorianCalendar#add has this section:

 case DAY_OF_MONTH: // synonym of DATE
 case DAY_OF_YEAR:
 case DAY_OF_WEEK:
    break;
Thilo
Thanks for the source confirmation.
Haes
The behaviour of over-/underflow when using the add method is well defined in the API documentation: "Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range." So overflowing the DAY_OF_MONTH field, means that the MONTH field (next larger) is incremented and the DAY_OF_MONTH field set to 1 (adjusted back into its valid range).
jarnbjo
@jarnbjo: and I think the exact same thing happens for DAY_OF_YEAR, DAY_OF_WEEK and DATE.
Thilo