Skip to content
Advertisement

Loop through Months in Java / Android

I want to loop through months of the year and print out.

for example:

01/2012 02/2012 03/2012 04/2012 etc…

Here is my code:

 Calendar myDate = Calendar.getInstance();

 for (int i = 0; i < totalMonths; i++) {
        TableRow row = new TableRow(this);
        myDate.add(Calendar.MONTH, i);
        FinalDate = df.format(myDate.getTime());
        TextView tvNum = new TextView(this);
        tvNum.setText("      " + FinalDate);
        row.addView(tvNum);
        table.addView(row);
    }
}

It is printing out in int’s

1 2 3 4 5

However, when I convert it to a date string, as seen in code above, it does this:

05/2012 06/2012 08/2012 11/2012 03/2013 08/2013

Basically, the gap of months is 1, then 2, then 3, then 4 etc… Are my calculations wrong? (showing the 1,2,3,4, etc list of int’s is doing what it is supposed to be) or is there a better way through printing out months?

I just want it to go

today’s date + 1 month today’s date + 2 months etc… this m

Advertisement

Answer

You’re adding i months to the current date each time.

Therefore, the third iteration adds 2 months to the previous date, the fourth adds 3, etc.

You should be adding just 1 month each time.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement