次の Linq クエリを使用できます。
int month = 1;
int year = 2013;
var cal = System.Globalization.CultureInfo.CurrentCulture.Calendar;
IEnumerable<int> daysInMonth = Enumerable.Range(1, cal.GetDaysInMonth(year, month));
List<Tuple<int, DateTime, DateTime>> listOfWorkWeeks = daysInMonth
.Select(day => new DateTime(year, month, day))
.GroupBy(d => cal.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday))
.Select(g => Tuple.Create(g.Key, g.First(), g.Last(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)))
.ToList();
// Item1 = week in year, Item2 = first day, Item3 = last working day
int weekNum = 1;
foreach (var weekGroup in listOfWorkWeeks)
{
Console.WriteLine("Week{0} = {1} {2} to {1} {3}"
, weekNum++
, System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month)
, weekGroup.Item2.Day
, weekGroup.Item3.Day);
}
1 月の出力:
Week1 = January 1 to January 4
Week2 = January 7 to January 11
Week3 = January 14 to January 18
Week4 = January 21 to January 25
Week5 = January 28 to January 31
2 月の場合:
Week1 = February 1 to February 1
Week2 = February 4 to February 8
Week3 = February 11 to February 15
Week4 = February 18 to February 22
Week5 = February 25 to February 28