0

给定“日期名称”,如何获取给定两个日期之间的所有日期?
例如:Start_Date = 2011 年 1 月 1 日
      End_Date = 2011 年1 月 20 日
      日期名称=星期日

在这里,我们需要获取所有日期名称为“SUNDAY”的日期
例如:

Jan 02, 2011
Jan 09, 2011
Jan 16, 2011
4

5 回答 5

12

我喜欢Enumerable.Range用于这样的任务:

DateTime start = new DateTime(2011,1,1);
DateTime end = new DateTime(2011,1,20);

var datesThatAreSundays = Enumerable
    .Range(start.DayOfYear, end.Subtract(start).Days + 1)
    .Select(n => start.AddDays(n - start.DayOfYear))
    .Where(d => d.DayOfWeek == DayOfWeek.Sunday);
于 2012-09-14T13:28:54.023 回答
2

像这样的东西怎么样

DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";

List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
    if (runDate.DayOfWeek.ToString().ToLower() == dayName)
        list.Add(runDate);
}

甚至使用Enum.TryParse

DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";
DayOfWeek dow;
Enum.TryParse(dayName, true, out dow);

List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
    if (runDate.DayOfWeek == dow)
        list.Add(runDate);
}
于 2012-09-14T13:26:29.517 回答
2
DateTime startDate = new DateTime(2011, 1, 1);
DateTime endDate = new DateTime(2011, 1, 20);

while (startDate < endDate)
{
   if (startDate.DayOfWeek == DayOfWeek.Sunday)
   {
      // Do something
   }

   startDate = startDate.AddDays(1);
}
于 2012-09-14T13:23:34.620 回答
0

未经测试:

DateTime start = x;
DateTime end = y;

while (start.DayOfWeek != z)
    start = start.AddDays(1);

while (start <= end)
{
    //DoStuff

    start = start.AddDays(7);
}
于 2012-09-14T13:26:34.583 回答
0

你可以试试这个

 var firstDate = new DateTime(2011, 1, 1);
 var lastDate = new DateTime(2011, 1, 20);

 var result = (from el in Enumerable.Range(0, (lastDate - firstDate).Days)
                      let date = firstDate.AddDays(el)
                      where date.DayOfWeek == DayOfWeek.Sunday
                      select date).ToArray();
于 2012-09-14T13:33:00.983 回答