Is a Date in a Leap Year in Java
Going back to my very first programming class in 1994, I learned how to design an algorithm that would tell whether a given date was in a leap year or not. We all know that every fourth year is a leap year. However, it gets a tiny bit tricky at the turn of the century because every year that is divisible by 100 is not a leap year, whereas every year that is divisible by 400 is a leap year. This is a way of correcting for precisely how long it takes the earth to orbit around the sun. In Java, it’s not too hard to find whether a year is a leap year without having to implement your own algorithm.
Here is your function:
public static boolean IsInLeapYear(Date date) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); return cal.isLeapYear(cal.get(cal.YEAR)); }
And here is how you would call it:
System.out.println(IsInLeapYear(Dates.CreateDate(2008, 2, 3))); // true System.out.println(IsInLeapYear(Dates.CreateDate(2007, 2, 3))); // false System.out.println(IsInLeapYear(Dates.CreateDate(2004, 2, 3))); // true System.out.println(IsInLeapYear(Dates.CreateDate(2000, 2, 3))); // true System.out.println(IsInLeapYear(Dates.CreateDate(2100, 2, 3))); // false