Detect a leap yearTag(s): Date and Time


The algorithm to determine is a given year is leap or not (>365 days) is :
if year modulo 400 is 0 then 
   leap
else if year modulo 100 is 0 then 
   no_leap
else if year modulo 4 is 0 then 
   leap
else 
   no_leap

Three techniques to check if a year is leap or not :

import java.util.Calendar;
import java.util.GregorianCalendar;

 
public class DateUtils {
  private DateUtils() {  }
  
  // using GregorianCalendar
  public static boolean isLeap0(int year) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.set(Calendar.YEAR, year);
    return cal.isLeapYear(cal.get(Calendar.YEAR));
  }
  
  // using a Calendar
  public static boolean isLeap1(int year) {
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.YEAR, year);
      return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
  }
  
  // directly, maybe faster...
  public static boolean isLeap2(int year) {
    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
  }
  

  public static void main(String[] args) {
    System.out.println("1900 : " + DateUtils.isLeap0(1900));
    System.out.println("1996 : " + DateUtils.isLeap0(1996));
    System.out.println("2000 : " + DateUtils.isLeap0(2000));
    System.out.println("2010 : " + DateUtils.isLeap0(2010));
    System.out.println("");
    System.out.println("1900 : " + DateUtils.isLeap1(1900));
    System.out.println("1996 : " + DateUtils.isLeap1(1996));
    System.out.println("2000 : " + DateUtils.isLeap1(2000));
    System.out.println("2010 : " + DateUtils.isLeap1(2010));
    System.out.println("");
    System.out.println("1900 : " + DateUtils.isLeap2(1900));
    System.out.println("1998 : " + DateUtils.isLeap2(1996));
    System.out.println("2000 : " + DateUtils.isLeap2(2000));
    System.out.println("2010 : " + DateUtils.isLeap2(2010));
  }
}

blog comments powered by Disqus