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 19, Windows 10
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);
}

Posted: March 20, 2023

Return to the snippets listing