Monday, 13 April 2015

SQL script to find if date is a part of Leap Year or Not - 1

There are times when we wish to check the date that we are dealing with belongs to the leap year or not. 
I came across such a situation and ended up designing a function for it. 
This function takes the date as an input and returns BIT value depending on whether year of the 
date passed qualifies as a leap year of not.

The logic that I used here is given below
  • Fetch the year of the date passed.
  • Using it form the first and last day of year
  • Calculate the difference between FirstDayOfYear and LastDayOfYear
CREATE FUNCTION udf_IsLeapyear(@InDate DATETIME)RETURNS BIT
AS
BEGIN

   DECLARE 
@YEAR VARCHAR(10),
           
@DATE VARCHAR(20)'-12-31'

   
SELECT @YEAR CONVERT(VARCHAR(10),DATEPART(YEAR,@InDate))
   
RETURN
   
(
    
SELECT
       
CASE
           
WHEN DATEDIFF(DAY,DATEADD(YEAR,-1,CONVERT(DATE,@YEAR+@DATE)),CONVERT(DATE,@YEAR+@DATE))=366 THEN 1
           ELSE 0
       END
    
)
END
 

No comments:

Post a Comment

bloggerwidgets