Tuesday, November 20, 2007

Finding a Leap Year

We all very well know what a leap year is? A year which has 366 days is called a leap year. But how many of us know how do you know which year is a leap year? Do you know which calendar year will have 29 days in the month of February?

Most of us have a very wrong perception of a Leap year. If you ask any person how do you calculate a Leap year? His obvious reply will be divide the year by 4, if it gets divided then it is a leap year. Well that seems to be very simple, so why do we need a function to calculate a leap year?

Actually leap year is some thing more then divide by 4. First you need to check whether a year gets divided by 4, if it gets divided by 4 then ensure that it does not get divided by 100, if it does not get divided by 100 then it is a leap year. But, if it gets divided by 100 then it should also get divided by 400 in order to be a leap year.


This function takes year as an input and returns 1, if it is a leap year and 0 if it is not a leap year.


CREATE OR REPLACE FUNCTION IsLeapYear
(
p_year IN NUMBER
)
RETURN NUMBER

IS

v_chkLeapYr NUMBER;
X NUMBER;

BEGIN


--**Leap Year Calculation

SELECT DISTINCT MOD(p_year, 4) INTO v_chkLeapYr FROM DUAL;

IF v_chkLeapYr = 0 THEN
IF mod(p_year,100) = 0 THEN --* If divided by 4 and not by 100 then LEAP YEAR
IF mod(p_year,400) = 0 THEN --* If divided by 4 and 100 then it should also get divided by 400 then LEAP YEAR
X := 366;
ELSE
X := 365;
END IF;
ELSE
X := 366;
END IF;
ELSE
X := 365;
END IF;

If x = 366 Then
Return (1); --* Lear Year
Else
Return (0);
End If;


END IsLeapYear;