Leon Meijer's Weblog

About my personal life, technology and business/work related...
posts - 128, comments - 334, trackbacks - 0

Get the First Day of a Week

How to get the date range by a week number? Well I was having that issue and I couldn't find code on the Internet (even after looking more than 10 minutes). Here's how I did it:

   1: public DateTime FirstDayOfWeek(int year, int weekNumber)
   2: {
   3:     // Get info about the current culture
   4:     CultureInfo info = Thread.CurrentThread.CurrentCulture;
   5:     DateTime dayInWeek1 = DateTime.MinValue;
   6:     // Check the Calender Week Rule (when is it week 1?)           
   7:     if (info.DateTimeFormat.CalendarWeekRule == CalendarWeekRule.FirstFourDayWeek)
   8:         dayInWeek1 = new DateTime(year, 1, 4); // For sure that this date is in week 1
   9:     else
  10:         dayInWeek1 = new DateTime(year, 1, 1); // For sure that this date is in week 1
  11:  
  12:     // Get a date from the weekNumber by adding 7*weeks to the 
  13:     // first week of the year
  14:     dayInWeek1 = dayInWeek1.AddDays(7 * (weekNumber-1));
  15:     DayOfWeek firstDay = DayOfWeek.Monday;
  16:     DateTime date = dayInWeek1;
  17:     while (date.DayOfWeek != firstDay)
  18:     {
  19:         // Go back a day till we found the monday
  20:         date = date.AddDays(-1);
  21:     }
  22:     return date.Date;
  23: }

Hope it helps,

Print | posted on Wednesday, September 10, 2008 5:12 AM |

Powered by: