如何在C#中的日期范围内获取所有周末

时间:2014-07-25 18:51:21

标签: c# .net date-range dayofweek weekend

我只是想知道是否有简单的方法或框架 在C#中获取日期范围内的所有周末?

是否也可以使用LINQ?

有任何线索吗?

谢谢!

3 个答案:

答案 0 :(得分:13)

如果您想要枚举所有日子,可以使用linq过滤到周末:

IEnumerable<DateTime> GetDaysBetween(DateTime start, DateTime end)
{
    for (DateTime i = start; i < end; i = i.AddDays(1))
    {
        yield return i;
    }
}

var weekends = GetDaysBetween(DateTime.Today, DateTime.Today.AddDays(365))
    .Where(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday);

答案 1 :(得分:1)

我找到了怎么做。

http://www.dotnetjalps.com/2011/06/finding-saturdaysunday-between-date.html

namespace DatimeApplication
{
   class Program
   {
       static void Main(string[] args)
       {
             DateTime startDate=new DateTime(2011,3,1);
             DateTime endDate = DateTime.Now;

             TimeSpan diff = endDate - startDate;
             int days = diff.Days;
             for (var i = 0; i <= days; i++)
             {
                 var testDate = startDate.AddDays(i);
                 switch (testDate.DayOfWeek)
                 {
                     case DayOfWeek.Saturday:
                     case DayOfWeek.Sunday:
                         Console.WriteLine(testDate.ToShortDateString());
                         break;
                 }
             }
           Console.ReadLine();
       }
   }
}

答案 2 :(得分:1)

编码并不困难......这是一个高效的迭代器:

public static IEnumerable<DateTime> GetWeekends(DateTime startDate, DateTime endDate)
{
    startDate = startDate.Date;
    endDate = endDate.Date;

    if (endDate < startDate)
        yield break;

    var currentDate = startDate;

    // Advance to next Saturday
    switch (currentDate.DayOfWeek)
    {
        case DayOfWeek.Saturday:
            break;

        case DayOfWeek.Sunday:
            yield return currentDate;
            currentDate = currentDate.AddDays(6);
            break;

        default:
            currentDate = currentDate.AddDays(DayOfWeek.Saturday - currentDate.DayOfWeek);
            break;
    }

    while (currentDate <= endDate)
    {
        yield return currentDate;

        currentDate = currentDate.AddDays(1);
        if (currentDate <= endDate)
            yield return currentDate;

        currentDate = currentDate.AddDays(6);
    }
}