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?

Jon Skeet
people
quotationmark

You need to set the calendar to be in that year and month before asking for the maximum value, e.g. with

cal.set(year, month, 1);

(Or with the calendar constructor as per David's answer.)

So:

public static int getMaxDaysInMonth(int month, int year) {
    Calendar cal = Calendar.getInstance();
    // Note: 0-based months
    cal.set(year, month, 1);
    return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}

Alternatively - and preferrably - use Joda Time or Java 8:

// Java 8: 1-based months
return new LocalDate(year, month, 1).lengthOfMonth();

// Joda Time: 1-based months
return new LocalDate(year, month, 1).dayOfMonth().getMaximumValue();

(I'm sure there must be a simpler option for Joda Time, but I haven't found it yet...)

people

See more on this question at Stackoverflow