Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for leap year

Tags:

tsql

math

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
like image 221
t-clausen.dk Avatar asked Jun 30 '11 12:06

t-clausen.dk


2 Answers

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'...
like image 141
gbn Avatar answered Oct 04 '22 11:10

gbn


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

like image 38
Kevin P. Rice Avatar answered Oct 04 '22 11:10

Kevin P. Rice