3

At the moment I have this code to return a table of all dates between 2 dates. How could I change this to have it only return the weekend dates. The purpose of this is to use the weekend dates to check against column headers in a DataGridView to "grey-out" the weekends. I hope that's clear.

static public List<string> GetDates(DateTime start_date, DateTime end_date)
{
    List<string> days_list = new List<string>();

    for (DateTime date = start_date; date <= end_date; date = date.AddDays(1))
    {
        days_list.Add(date.ToShortDateString());
    }

    return days_list;
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Josh
  • 115
  • 1
  • 3
  • 17

3 Answers3

11

Use the DateTime.DayOfWeek property.

https://msdn.microsoft.com/en-US/library/system.datetime.dayofweek(v=vs.110).aspx

static public List<string> GetDates(DateTime start_date, DateTime end_date)
    {
        List<string> days_list = new List<string>();
         for (DateTime date = start_date; date <= end_date; date = date.AddDays(1))
        {
            if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday)
                 days_list.Add(date.ToShortDateString());
        }

        return days_list;
Vitor Rigoni
  • 573
  • 4
  • 14
4

You can create range of dates and then filter on them using DayOfWeek as @Vitor said:

static public List<DateTime> GetWeekendDates(DateTime start_date, DateTime end_date)
{
 return Enumerable.Range(0, (int)((end_date- start_date).TotalDays) + 1)
                  .Select(n => StartDate.AddDays(n))
                  .Where(x=>x.DayOfWeek == DayOfWeek.Saturday 
                         || x.DayOfWeek == DayOfWeek.Sunday)
                  .ToList();
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
3

hope this solution will help you

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

in above code I am finding Saturday and Sunday between 1st March 2011 and today. So I have taken two variables called startDate and endDate. After that I have got difference between them and then via for loop I am checking that day of week is Saturday or Sunday

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Pritish
  • 2,194
  • 2
  • 21
  • 44