Number of Days in Given Month

Description: Returns an integer representing the number of days for a given month of a given year in the Julian/Gregorian calendars. Requires java.util.GregorianCalendar
Tested Platform: Java SE 7, Windows 7
Language: Java
// Returns the number of days for a given month of a given year according to
// Julian (up to 1582) or the GregorianCalendar (1582 onwards)
// Months start from 0 = January

public int numberOfDays(int month, int year) {
    	GregorianCalendar cal = new GregorianCalendar();
    	cal.set(GregorianCalendar.MONTH, month);
    	cal.set(GregorianCalendar.YEAR, year);
    	return cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
}

Submitted: January 15, 2013

Return to the snippets listing