How do I check if a year is a leap year?
I have this code:
declare @year int
set @year = 1968
SELECT CASE WHEN @YEAR = THEN \'LEAP
I Have a better solution
CREATE FUNCTION dbo.IsLeapYear(@year INT)
RETURNS BIT AS
BEGIN
DECLARE @d DATETIME,
@ans BIT
SET @d = CONVERT(DATETIME,'31/01/'+CONVERT(VARCHAR(4),@year),103)
IF DATEPART(DAY,DATEADD(MONTH,1,@d))=29 SET @ans=1 ELSE SET @ans=0
RETURN @ans
END
GO
feel free to use
Not sure how efficient this is compared to the other solutions. But is another option.
DECLARE @year int = 2016
SELECT CASE
WHEN DATEPART(dayofyear, DATEFROMPARTS(@year, 12, 31)) = 366
THEN 'LEAP'
ELSE 'NOT LEAP'
END
Check for 29th Feb:
CASE WHEN ISDATE(CAST(@YEAR AS char(4)) + '0229') = 1 THEN 'LEAP YEAR' ELSE 'NORMAL YEAR' END
or use the following rule
CASE WHEN (@YEAR % 4 = 0 AND @YEAR % 100 <> 0) OR @YEAR % 400 = 0 THEN 'LEAP YEAR'...
3 line... but could be also 2...
DECLARE @Y as int = 2021;
DECLARE @Dt as char(10) = CAST(@Y as CHAR(4)) + '-02-29'
SELECT IIF(isDATE(@Dt) = 1, 1,0)
or
DECLARE @Dt as char(10) = '2020-02-29'
SELECT IIF(isDATE(@Dt) = 1, 1,0)
Alen
This could also help
DECLARE @year INT = 2012
SELECT IIF(DAY(EOMONTH(DATEFROMPARTS(@year,2,1))) = 29,1,0)
Result: 1 --(1 if Leap Year, 0 if not)
SELECT IIF(DAY(EOMONTH(DATEFROMPARTS(@year,2,1))) = 29,'Leap year','Not Leap year')
Result: Leap year
MOST EFFICIENT LEAP YEAR TEST:
CASE WHEN @YEAR & 3 = 0 AND (@YEAR % 25 <> 0 OR @YEAR & 15 = 0) THEN ...
Adapted from: http://stackoverflow.com/a/11595914/3466415