Search code examples
c#.netdate-rangedayofweekweekend

How to get all weekends within a date range in C#


Is there a simple way or framework to get all weekends within a date range in C#?

Is it possible to do with LINQ as well?


Solution

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