It very much depends on your culture on what calendar week you have.
Continental Europe (e.g. ISO8601 based) is different to UK and US, and others...
This gives the first date of a given week, depending of your culture settings:
1 private static DayOfWeek FirstDay
2 { get { return CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; } }
3 private static CalendarWeekRule WeekRule
4 { get { return CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule; } }
5 private static int GetWeek(DateTime date)
6 {
7 return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.Date, WeekRule, FirstDay);
8 }
9 private static DateTime FirstDateOfWeek(DateTime date)
10 {
11 return date.Date.AddDays(-((7 + date.Date.DayOfWeek - FirstDay) % 7));
12 }
13 private static DateTime FirstDateOfWeek(int year, int week)
14 {
15 DateTime dt = new DateTime(year, 1, 1);
16 if (GetWeek(dt) == 1) dt = dt.AddDays(-7);
17 return FirstDateOfWeek(dt.AddDays(week * 7));
18 }
19 public static IEnumerable<DateTime> WeekDaysOfWeek(DateTime date)
20 {
21 DateTime firstDayOfWeek = FirstDateOfWeek(date);
22 foreach (int d in Enumerable.Range(0, 7)) yield return firstDayOfWeek.AddDays(d);
23 }
24 public static IEnumerable<DateTime> WeekDaysOfWeek(int year, int day)
25 {
26 return WeekDaysOfWeek(FirstDateOfWeek(year, day));
27 }
Usage:
57 var culture = CultureInfo.CurrentCulture;
58 Console.WriteLine("Today = {0}", DateTime.Today.ToString("ddd yyyy-MM-dd"));
59 Console.WriteLine("Rule = {0}", WeekRule);
60 Console.WriteLine("Day1 = {0}", FirstDay);
61 Console.WriteLine("Week = {0}", GetWeek(DateTime.Today));
62
63 foreach (var item in WeekDaysOfWeek(2012, GetWeek(DateTime.Today)))
64 {
65 Console.WriteLine("{0}", item.ToString("ddd yyyy-MM-dd"));
66 }
Output:
Today = Fr 2012-03-30
Rule = FirstFourDayWeek
Day1 = Monday
Week = 13
Mo 2012-03-26
Di 2012-03-27
Mi 2012-03-28
Do 2012-03-29
Fr 2012-03-30
Sa 2012-03-31
So 2012-04-01