Check for leap year

2020-02-06 05:14发布

问题:

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 = <LEAPYEAR> THEN 'LEAP YEAR' ELSE 'NORMAL YEAR' END

Expected result:

LEAP YEAR

回答1:

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'...


回答2:

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



回答3:

Leap year calculation:

(@year % 4 = 0) and (@year % 100 != 0) or (@year % 400 = 0)

When this is true, then it is a leap year. Or to put it in case statement

select case when
    (
        (@year % 4 = 0) and (@year % 100 != 0) or
        (@year % 400 = 0)
    ) then 'LEAP' else 'USUAL' end
;


回答4:

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 


回答5:

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



标签: tsql math