1: // General Idea:
2: // We want to have some that in the the week we want to calculate
3: // the start and the end date for. For this, we are going to
4: // calculate the week of january 1st, add the number of weeks to
5: // this date so that we have a date in the target week. Now go
6: // back until we reach the first day of the corresponding
7: // week and then add 6 days to get the last day in the week
8:
9: // first, get the week number for January 1st for the
10: // specific year
11: int jan1stWeekNumber =
12: CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
13: new DateTime(Year, 1, 1),
14: CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule,
15: CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
16:
17: int offset;
18: // We need an offset to add the number of weeks to jan 1st
19: // because this date may not be in the first week of the year.
20: // Examples (we want a date in week 23):
21: // jan 1st = week 1: week 1 + week 23 = week 24
22: // jan 1st = week 52 of last year: week 52 + week 23 = week 23
23: // now differ between the following two cases:
24: // 1. january 1st is in the last week of the previous year
25: // 2. january 1st is in the first week of the same year
26: if (jan1stWeekNumber == 1)
27: offset = 1;
28: else
29: offset = 0;
30:
31: // now add the week number including the offset to jan 1st
32: DateTime dateInWeek =
33: CultureInfo.CurrentCulture.Calendar.AddWeeks(
34: new DateTime(Year, 1, 1),
35: WeekNr - offset);
36:
37: // create dummy dates for first and last weekday
38: DateTime firstDateInWeek = new DateTime(
39: dateInWeek.Year,
40: dateInWeek.Month,
41: dateInWeek.Day);
42: DateTime lastDateInWeek;
43: // go back from the current date until we get to the first day
44: // of the week, of course, depending on the current culture
45: // (in U.S. the first day is sunday, in europe, monday)
46: while (firstDateInWeek.DayOfWeek !=
47: CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
48: {
49: firstDateInWeek = firstDateInWeek.AddDays(-1);
50: }
51: // to get the last day of the week, just add 6 days to the
52: // start day
53: lastDateInWeek = firstDateInWeek.AddDays(6);