JAVATM MASTER

Leap Year Algorithm

Back to Table of Contents

Today, leap year is calculated as occuring almost every four years. More precisely it is every year divisible by 4 that is not divisible by 100, unless it is also divisible by 400.

Hence, 1996, 2000, and 2004 are leap years, but 1900 and 2100 are not. Year 2000 is a leap year becuase it is divisible by 400. Here is the JavaTM code for this alogorithm:

public static boolean isLeapYear(int year) {
    if (year % 4 != 0) {
        return false;
    }
    if (year % 400 == 0) {
        return true;
    }
    return (year % 100 != 0);
}

The number of days of the month go by this poem:

Thirty days has September,
April, June, and November;

All the rest have thirty-one,

Except February which will alternate

Between twenty-nine on leap year

And a normal twenty-eight.

You can use an array to encapsulate the months as follows:

public static final int days_in_month[] = new int[]
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

//Where January is days_in_month[0] and December is days_in_month[11]:

public static final int JANUARY=0, FEBRUARY=1, MARCH=2, APRIL=3,
    MAY=4, JUNE=5, JULY=6, AUGUST=7, SEPTEMBER=8, OCTOBER=9,
    NOVEMBER=10, DECEMBER=11;

//be sure to remember array starts at 0 -- there is no month 12.

public static int getDaysInMonth(int Mon, int Year){
	if (Mon != FEBRUARY)
		return days_in_month[Mon];
	return isLeapYear(Year) ? 29 : 28;
}
	
int NumDays = getDaysInMonth(FEBRUARY, 2000);

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*