如何在c#中获得一个日期范围内的所有周末

本文关键字:日期 一个 范围内 周末 | 更新日期: 2023-09-27 18:14:58

是否有一种简单的方法或框架来获得c#中日期范围内的所有周末?

也可以用LINQ来做吗?

如何在c#中获得一个日期范围内的所有周末

如果你想枚举所有的日子,你可以使用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);

我知道怎么做了。

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();
       }
   }
}

这并不难编写…下面是一个高效的迭代器:

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);
    }
}