Can anyone tell me what is wrong with the following code? It adds the 14 days to the object just fine but when it adds 14 days to Feb 17th it should come up with March 2, 2012 this year, but instead I am getting Feb 31, 2012. I have tried adding 2 weeks, single days in a for loop and everything keeps coming back to the same date. I have spent two days searching google and reading as much as I can but no luck. Hoping someone here can see something I am missing.
while(calNextPaymentDate.before(calEnd))
{
Dates.add(date);
calNextPaymentDate.add(Calendar.DAY_OF_MONTH, 14);
date = (GregorianCalendar) calNextPaymentDate.clone();
}
The calNextPaymentDate and calEnd are GregorianCalendar objects and I have done traces to make sure that the dates are being filled in fine. It is adding 14 days correctly to the dates, but as I said I should not be getting a Feb 31, 2012 data at all.
My guess is that actually you’ve set the month to 2, so you’re looking at March instead of February.
Try printing out the date – I very much doubt that it will show Feb 31st.
Don’t forget that
java.util.Calendarchose to use 0-based months, so for February you want month 1.