Thursday, December 22, 2011

How to get week of given date

In many scenario we need to prepare records weekly basis.Such a cases we want to find week of the given date.I wrote a t-sql tip for to get week of given date.

For Eg , consider 19th november 2011 is given date.The Datepart (wk,<Date>) function will returns the week of the year.So we get result is 47 then take first day (01-Nov-2011) of the given date and applying the same Datepart function formula so we get result 45. Then subtract the result from earlier result with this (47 - 45) after subtraction result add with 1. Finally we get the result is 3. So we can say  the 19th november 2011 is in the third week.

Declare @Dt    DateTime = '19 nov 2011'


Select Datepart(wk, @Dt) - Datepart(wk, Dateadd(Day, - Day(@Dt) + 1,@Dt)) + 1

No comments:

Post a Comment