Number of days in particular month of particular year?

Java 8 and later

@Warren M. Nocos.
If you are trying to use Java 8’s new Date and Time API, you can use java.time.YearMonth class. See Oracle Tutorial.

// Get the number of days in that month
YearMonth yearMonthObject = YearMonth.of(1999, 2);
int daysInMonth = yearMonthObject.lengthOfMonth(); //28  

Test: try a month in a leap year:

yearMonthObject = YearMonth.of(2000, 2);
daysInMonth = yearMonthObject.lengthOfMonth(); //29 

Java 7 and earlier

Create a calendar, set year and month and use getActualMaximum

int iYear = 1999;
int iMonth = Calendar.FEBRUARY; // 1 (months begin with 0)
int iDay = 1;

// Create a calendar object and set year and month
Calendar mycal = new GregorianCalendar(iYear, iMonth, iDay);

// Get the number of days in that month
int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28

Test: try a month in a leap year:

mycal = new GregorianCalendar(2000, Calendar.FEBRUARY, 1);
daysInMonth= mycal.getActualMaximum(Calendar.DAY_OF_MONTH);      // 29

Leave a Comment