Detect a leap year
From CodeCodex
Contents
Implementations[edit]
Erlang[edit]
is_leap_year(Year) when Year rem 400 =:= 0 -> true; is_leap_year(Year) when Year rem 100 =:= 0 -> false; is_leap_year(Year) when Year rem 4 =:= 0 -> true; is_leap_year(_) -> false.
Java[edit]
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)); } }
Ruby[edit]
def leap_year?(year) year % 4 == 0 && year % 100 != 0 || year % 400 == 0 end
or
require 'date' Date.new(year).leap?
Seed7[edit]
This following function is part of the "time.s7i" library. It returns TRUE if the year is a leap year in the Gregorian calendar:
const func boolean: isLeapYear (in integer: year) is return (year rem 4 = 0 and year rem 100 <> 0) or year rem 400 = 0;
Original source: [1]