Get the Monday date of a given week in a given year

A user on Silverlight forum made me to write this post.

Quoting the user question:
"I want to get first and last date of week given by a week number and year"

For example if Week Number is 26 and Year is 2009, then the output must be 29/06/2009.

However I did the first date of given week and year, here is what the logic is:

1) Get the date of the first day of the given year. That is the first date of any year would be Year + "-1-1".
2) Find out the date of the monday of this week. For example, for 2009, the first monday date would be 12-29-2008.
3) Now, when we add (number of weeks * 7) to the very first monday, we get the monday of the given week and given year.

Thats all we have to do.

Here is the sample code:

int iWeek = 26;
int iYear = 2009;
DateTime firstDayOfYear;
DateTime firstMondayOfYear;
DateTime finalDate;
//Step 1
firstDayOfYear = Convert.ToDateTime(iYear.ToString() + "-1-1");
DayOfWeek t = 1 - firstDayOfYear.DayOfWeek + 1;
int intDayOfWeek = (int)firstDayOfYear.DayOfWeek;
//Step 2
firstMondayOfYear = firstDayOfYear.AddDays(1 - intDayOfWeek).Date;
//Stpe 3
finalDate = firstMondayOfYear.AddDays((iWeek) * 7);
 
finalDate will have 6/29/2009.
 
Happy coding  :)

2 comments:

  1. Year 1905, Week 1 - your code returns a 09 Jan, but first week in this year is at 02 Jan.
    Year 2007 is wrong too.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete