我有一个接受“月”和“年”输入的表格,我在这里写的是关于如何获得所有“工作周”的任何想法吗?

我的意思是“工作周”为星期一至星期五

所以基本上我需要第1周到第4周,或者如果需要的话,包括第5周。

例如,如果我输入2013年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


我该如何实现?谢谢你的帮助!任何建议或想法将不胜感激。谢谢队友! :)

最佳答案

您可以使用以下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);
}


一月份的输出:

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


对于二月:

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

09-11 06:42