2

我有一个接受“月”和“年”输入的表格,我在这里写信是为了询问我将如何获得所有“工作周”的任何想法?

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

所以基本上我需要第 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

我怎样才能做到这一点?谢谢你的帮助!任何建议或想法将不胜感激。谢谢小伙伴们!:)

4

3 回答 3

4

你可以使用这个 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
于 2013-01-17T16:51:46.333 回答
0

查找月份和年份的第一个星期一。

int year = 2013;
int month = 1;

DateTime testDate = new DateTime(year,month,1);


while ( testDate.DayOfWeek != DayOfWeek.Monday )
{
   testDate = testDate.AddDays(1);
}

然后每周迭代,直到你到达不是 2013 年的年份。

// Should have first monday now.
// Loop until the month changes
while ( testDate.Month == month)
{
   var monday = testDate;
   var friday = testDate.AddDays(4);

   // You now have both dates.  Do whatever you need to.
   // here.

   // Increment test date by a week
   testDate = testDate.AddDays(7)
}
于 2013-01-17T16:25:25.897 回答
0

在伪代码中:

  1. 从每月的第一天开始

  2. 虽然(天!=星期一)取下一个日期(+1天)

    请参阅此 SO 帖子(Jon Skeet 回答!)以检查一天是否为星期一。

  3. 添加 4 天以找到工作周的结束时间

    如果是在同一个月,那么您有一个工作周的时间来回答。

  4. 加 7 天查找下周一

  5. 如果新的星期一仍在同一个月内:重复 3. 和 4。

编辑上面找到所有完整的工作周。

还要找到其他周:

  • 如果该月的第一天已经是工作日,则查找下一个星期五。-> 第一个工作周
  • 如果最后一个星期五在下个月,则在该月的最后一天完成最后一个工作周。-> 上一个工作周
于 2013-01-17T16:28:58.333 回答