How to find out if the year is a LEAP year

Here's a simple script that can detect if the current year is a LEAP year. You can create a function out of this query and use it in your projects to detect if the year is a leap year and take decisions based on the same.

-- Detect if the year is a LEAP year

DECLARE @dt datetime
DECLARE @yr int
DECLARE @y char(4)
SET @dt = GETDATE()
SET @yr = YEAR(@dt)
SET @y = CAST(@yr as char(4))

SELECT CASE
-- Years like 2000, 2400 are always leap years
WHEN @yr % 400=0 then @y + ' is a Leap Year'
-- Years like 1700, 1900 divisible by 100
-- but not divisible by 400, are not leap years
WHEN @yr % 100=0 then @y + ' is not a Leap Yr'
-- Years like 2004 that are not divisible by
-- 400 and 100 but are divisible by 4, are leap years
WHEN @yr % 4=0 then @y + ' is a Leap Year'
ELSE @y + ' is not a Leap Yr'
END
AS LeapYearDetection

1 comment:

  1. there's an easier way to do this by letting sql server do the work for you

    if datepart(dd, cast(cast(datepart(yy, getdate()) as varchar) + '-02-28' as datetime) + 1) = 29
    print 'leap year'
    else
    print 'not a leap year'

    ReplyDelete