Check for leap year

前端 未结 7 2265
花落未央
花落未央 2020-12-11 01:19

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          


        
相关标签:
7条回答
  • 2020-12-11 02:03

    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

    0 讨论(0)
  • 2020-12-11 02:03

    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
    
    0 讨论(0)
  • 2020-12-11 02:04

    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'...
    
    0 讨论(0)
  • 2020-12-11 02:14

    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

    0 讨论(0)
  • 2020-12-11 02:16

    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 
    
    0 讨论(0)
  • 2020-12-11 02:20

    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

    0 讨论(0)
提交回复
热议问题