Karl
Karl

Reputation: 3464

Trouble with Android - Calendar.get() returning the wrong value

I have seen other posts regarding the way Calendar objects work on Android/Java and I'm aware of the 0 based nature of the way it works. This issue seems (to me) to be different so I've posted a new question. Forgive me if it's a dupe.

I'm having an issue with returning an array which I've populated with the month/year of every month upto 1 year ago. For example the desired outcome is:

PastMonth is a simple object consisting of two integers, month/year and a string representation - "July 2013".

Calendar rightNow = Calendar.getInstance();

PastMonth[] dateList = new PastMonth[12];
dateList[0] = new PastMonth(rightNow.get(Calendar.MONTH), rightNow.get(Calendar.YEAR));
for (int i=1; i<=11; i++) {
    Calendar monthsAgo = Calendar.getInstance();
    int month = monthsAgo.get(Calendar.MONTH);
    monthsAgo.set(Calendar.MONTH, month - i);
    dateList[i] = new PastMonth(monthsAgo.get(Calendar.MONTH), monthsAgo.get(Calendar.YEAR));
}

This all works fine apart from February. I end up with January, and then 2 entries for March. So:

I'm confused why this is happening because if I place a watch on the monthsAgo object I can see the month value is set to 1, which is February due to the Calendar object being a 0 based array, but when I call monthsAgo.get(Calendar.MONTH) it's return 2. Otherwise the rest of the array looks fine and is the desired outcome.

I might have missed something simple here, I suspect it's something to do with January being 0 and February being 1 but I can't piece it together.

Upvotes: 1

Views: 438

Answers (1)

Adam Lopresto
Adam Lopresto

Reputation: 346

Instead of monthsAgo.set(Calendar.MONTH, month - i);, try monthsAgo.add(Calendar.MONTH, -i);. The issue is that (if you're executing it right now), you're ending up with February 29th, 2013 (internally), which becomes March 1, once everything is normalized. You'll want to look at the documentation for Calendar with its set, add, and roll methods, but in this case, I think add is what you want.

Upvotes: 2

Related Questions