Search This Blog

Wednesday, 13 August 2008

Determine a Leap Year?

Armando Prato Armando Prato had written a SQL tip on how to determine a leap year the trick used is pretty neat, His example is in TSQL as below , but i guess we could use the idea in any language

   1: create function dbo.fn_IsLeapYear
   2:  (@year int)
   3: returns bit
   4: as
   5: begin    
   6:    return
   7: (select 
   8:     case datepart(mm, dateadd(dd, 1, cast((cast(@year as varchar(4)) + '0228') as datetime)))     
   9:     when 2 then 1     else 0     
  10:     end
  11: )
  12: end
  13: go

I like the idea of appending 0228 to the year and finding out if it is a leap year, The function takes in the year, appends '0228' to it (for February 28th) and adds a day. If the month of the next day is a 2, then we're still in February so it must be a leap year!  If not, it is not a leap year.

In C# this could be something like , I just thought its worth mentioning this on the blog for my record at the least

   1: bool isLeapYear = ((new DateTime(<int year value>, 02, 28)).AddDays(1).Date.Month.ToString() == "2")

2 comments:

Sly Gryphon said...

Or just use DateTime.IsLeapYear()

(Your example is back to front -- how would Add() know what the next day is without first working out if it is a leap year.)

TSQL.Net - Sri's Blog said...

Well didnt know about this back in 2008 .. now i do i suppose :)