Search code examples
javacalendardaysjava.util.calendar

How to get the number of days in a specific month using Java Calendar?


I am creating a simple program that allows the user to see how many days between the months they set.

For example From January - March

I can get the current day of the month using this:

Calendar.DAY_OF_MONTH

What I want is how can I supply a value in the month?

I have this simple code:

public static void machineProblemTwo(int startMonth, int endMonth) {

        int[] month = new int[0];
        int date = 2015;

        for(int x = startMonth; x <= endMonth; x++) {
           System.out.println(x + " : " + getMaxDaysInMonth(x,date));
        }

    }

public static int getMaxDaysInMonth(int month, int year){

        Calendar cal = Calendar.getInstance();
        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // how can I supply the month here?

        return days;

    }

How can i do that? Can you help me with this?


Solution

  • Use the constructor for GregorianCalendar where you pass the year, month and day. Don't forget that the months go from 0 to 11 (0 for January, 11 for December).

    public static int numberOfDaysInMonth(int month, int year) {
        Calendar monthStart = new GregorianCalendar(year, month, 1);
        return monthStart.getActualMaximum(Calendar.DAY_OF_MONTH);
    }