Creating a function check if a year is a leap year
This simple function checks the year passed in and returns true or false dependent on the year with one line of code
Usage
This simple little function is normally called by other database operation calculating age and year differences.
When you run DATEPART DAYOFYEAR and compare the number of days on 3rd March then a leap year will return one more day, which is correct, but needs to be coded around for calculating someones age.
To get around this, we append this function to one of the dates to subtract one day after February 29.
Get Leap Year
CREATE FUNCTION Dates.GetLeapYear(@Date DATETIME2) RETURNS BIT AS BEGINDECLARE @Ret BIT=(CASE WHEN DATEPART(YEAR,@Date)%4<>0 OR (DATEPART(YEAR,@Date)%100=0 AND DATEPART(YEAR,@Date)%400<>0) THEN 0 ELSE 1 END)RETURN @RetENDGO
Test
SELECT [dbo].[GetLeapYear]('01-01-1900') [1900],[dbo].[GetLeapYear]('01-01-1901') [1901],[dbo].[GetLeapYear]('01-01-1902') [1902],[dbo].[GetLeapYear]('01-01-1903') [1903],[dbo].[GetLeapYear]('01-01-1904') [1904]
Result
Only 1904 will return true as expected.