How to get all weekends within date range in C# [closed]

拟墨画扇 提交于 2019-12-10 10:39:15

问题


I am just wondering if there is a simple way or framework to to get all weekends within date range in C#?

Is it possible to do with LINQ as well?

Any clue?

Thank you!


回答1:


If you make a way to enumerate all days, you can use linq to filter to weekends:

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



回答2:


I found how to do it.

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



回答3:


That's not really difficult to code... Here's an efficient iterator:

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


来源:https://stackoverflow.com/questions/24962613/how-to-get-all-weekends-within-date-range-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!