Search code examples
javagregorian-calendar

Issue with Gregorian Calendar


We are using the below code snippet to get number of days for the provided month and year. For 02 and 2011, It returns the no of days as 31 ( which is not the case). for 02 and 2016, it returns the no of days as 29.

Any clues.

package Processes.BSAInvoiceInquiry.ExternalCall.PaymentStatusInquiry;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class PaymentStatusInquiryJavaCode {

    protected int year = 0;
    protected int month = 0;
    protected int days = 0;

    public void invoke() throws Exception {

        PaymentStatusInquiryJavaCode a = new PaymentStatusInquiryJavaCode();

        System.out.println("Year  " + year);
        System.out.println("Month  " + month);

        Calendar calObj = new GregorianCalendar();
        calObj.set(Calendar.YEAR, year);
        calObj.set(Calendar.MONTH, month - 1);
        System.out.println("Month  " + Calendar.MONTH);
        int numDays = calObj.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.println("No of the days in the month is   " + numDays);
        days = numDays;

    }
}

Solution

  • This is just another unexpected behavior of Calendar, see this, you can fix it by clear after the creation:

    Calendar calendar = new GregorianCalendar();
    calendar.clear();
    calendar.set(Calendar.YEAR, 2011);
    calendar.set(Calendar.MONTH, 1);
    System.out.println(calendar.getActualMaximum(calendar.DAY_OF_MONTH)); //28
    

    The use of outdated Calendar should be avoided. In java8, this can be done by:

    YearMonth yearMonth = YearMonth.of(2011, 2);
    int lengthOfMonth = yearMonth.lengthOfMonth();
    System.out.println(lengthOfMonth); //28