Monday, 13 April 2015

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

In my previous blog entry on the same topic, I have mentioned the logic and function used to find the Leap year. 

In this article with little bit tweak in the logic we are trying to find the same information. 

I haven't included this script as a part of function. This is standalone script which would return 1 or 0 depending on whether the evaluated date is from a leap year or not.

The logic used this time around is given below


  • Fetch the year for the passed date
  • form 2 dates using it - first day of Feb and of March for the Year
  • Find the difference between these two dates - If 29 then then is a leap year else it is not.


/*

You may intialize @Date to anydate that you want to validate

*/

DECLARE @DATE DATETIME = GETDATE() -- DATEADD(YEAR,-3,GETDATE())
SELECT
  
CASE
  DATEDIFF
(DAY,'02/01/' CONVERT(VARCHAR(4),YEAR(@DATE)),'03/01/' CONVERT(VARCHAR(4),YEAR(@DATE)))
   
WHEN 28 THEN 0
   ELSE 1
  END AS IsLeapYear
 

No comments:

Post a Comment

bloggerwidgets