javafor-loopcalendar

Java How to use for loop to populate Year and Month list?


How can I loop year and months to display below output? Limit of the period to show is current month and year Also, show 3 years inclusive of the year as of date. Meaning if its 2019 now, show 2018 and 2017.

I tried with some code to run as java application in hope to get the expected output below but this is what I've tried and got.

Would appreciate much if anyone can shed some light here.

public class TestClass {
public static void main(String[] args) {
    Calendar today = Calendar.getInstance();
    //month=5, index starts from 0
    int month = today.get(Calendar.MONTH);
    //year=2019
    int year = today.get(Calendar.YEAR);

    for(int i = 0; i < 3; i++) {    //year
        for(int j= 0; j <= month; j++) {    //month
        System.out.println("Value of year: " + (year - 2)); //start from 2017 and iterate to 2 years ahead
        System.out.println("Value of month: " + (month + 1)); //start from January (index val: 1) and iterate to today's month
        }
    }
}

}

Expected Output:

2017 1 2017 2 2017 3 2017 4 2017 5 2017 6 2017 7 2017 8 2017 9 2017 10 2017 11 2017 12

2018 1 2018 2 2018 3 2018 4 2018 5 2018 6 2018 7 2018 8 2018 9 2018 10 2018 11 2018 12

2019 1 2019 2 2019 3 2019 4 2019 5 2019 6


Solution

  • Try below code. I'm using java 8 and java.time.LocalDate,

    LocalDate currentDate = LocalDate.now();
    int year = currentDate.getYear();
    int month = currentDate.getMonthValue();
    
    for (int i = year - 2; i <= year; i++) {
        for (int j = 1; j <= 12; j++) {
            if (i == year && j == month) {
                System.out.print(i + " " + j + " ");
                break;
            }
                System.out.print(i + " " + j + " ");
            }
        }
    }
    

    Output

    2017 1 2017 2 2017 3 2017 4 2017 5 2017 6 2017 7 2017 8 2017 9 2017 10 2017 11 2017 12 2018 1 2018 2 2018 3 2018 4 2018 5 2018 6 2018 7 2018 8 2018 9 2018 10 2018 11 2018 12 2019 1 2019 2 2019 3 2019 4 2019 5 2019 6