Sunday, October 26, 2008

How to check for leap year?

Checking leap year is one of the most common checks that I perform in date values. Wikipedia have this pseudo-code to calculate for leap year:
if ((year modulo 4 is 0) and (year modulo 100 is not 0)) or
(year modulo 400 is 0) then

leap
else
not_leap
I've been using this algorithm all my programming life, and there's really nothing wrong with it. SQL Server, however, can accurately handle date data and have a couple functions that can be used to check for leap year without passing through this complicated algorithm. What I did is just to check if the expression is a valid date expression using the ISDATE() function.

Running the queries below:
select isdate('20070229') as validdate
select isdate('20080229') as validdate
will return the following result sets:
validdate
-----------
0
validdate
-----------
1
So if I have an integer year variable, I just need to build the date string.
set nocount on
declare @YearVar int

set @YearVar = 2007
select
isdate(cast(@YearVar as varchar(4)) + '0229') as validdate


set @YearVar = 2008
select
isdate(cast(@YearVar as varchar(4)) + '0229') as validdate
Here are the result sets:
validdate
-----------
0

validdate
-----------
1
To ensure that the date string will be properly interpreted, I use the unseparated date string format. For more on that, read my old notes.

Here's a sample code that illustrate how this algorithm works:
set nocount on
declare @YearVar int

set @YearVar = 2007
select
@YearVar as YearVar,

case
when isdate(cast(@YearVar as varchar(4)) + '0229') = 1 then

'leap year'
else 'not leap year'
end as validdate

YearVar validdate
----------- -------------
2007 not leap year


set @YearVar = 2008
select
@YearVar as YearVar,

case
when isdate(cast(@YearVar as varchar(4)) + '0229') = 1 then

'leap year'
else 'not leap year'
end as validdate

YearVar validdate
----------- -------------
2008 leap year


~~CK

No comments:

Post a Comment