Eric
Eric

Reputation: 83

I am having issues with adding 14 days to a java Calendar object, keeps giving me Feb 31, 2012

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.

Upvotes: 1

Views: 192

Answers (2)

user1076637
user1076637

Reputation: 768

One alternative is to use Time instead of Calendar.

http://developer.android.com/reference/android/text/format/Time.html

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500425

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.Calendar chose to use 0-based months, so for February you want month 1.

Upvotes: 6

Related Questions