Main Tutorials

Java – How to calculate leap year

A leap year is a year containing one additional day (366 days a year). Review the leap year algorithm :


if year is divisible by 400 then
   is_leap_year
else if year is divisible by 100 then
   not_leap_year
else if year is divisible by 4 then
   is_leap_year
else
   not_leap_year

P.S Algorithm from wikipedia leap year.

1. Java Leap Year Example

Java example to determine if the given year is a leap year.

DateTimeExample.java

package com.mkyong.utils;

public class DateTimeExample {

    public static void main(String[] args) {

	DateTimeExample obj = new DateTimeExample();
	System.out.println("1993 is a leap year : " + obj.isLeapYear(1993));
	System.out.println("1996 is a leap year : " + obj.isLeapYear(1996));
	System.out.println("2012 is a leap year : " + obj.isLeapYear(2012));

    }

    public boolean isLeapYear(int year) {

	if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
		return true;
	} else {
		return false;
	}
    }
	
}

Output


1993 is a leap year : false
1996 is a leap year : true
2012 is a leap year : true

2. GregorianCalendar Example

Alternatively, you can use GregorianCalendar.isLeapYear() API.


    import java.util.GregorianCalendar;
	
    //...
    public boolean isLeapYear(int year) {

	GregorianCalendar cal = (
		GregorianCalendar) GregorianCalendar.getInstance();

	return cal.isLeapYear(year);
    }

References

  1. Wikipedia : Leap Year
  2. Wikipedia : Gregorian calendar
  3. GregorianCalendar Java doc

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Acid
10 years ago

public boolean isLeapYear(int year) {
return ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)));
}

It should doing the same, however it is a nice article.

SiddarthRaj
10 years ago

Useful stuff

KevinR
10 years ago

Wikipedia algorithm is inefficient. Instead, use:

“return ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0));”. See: http://stackoverflow.com/a/11595914/733805)