如何返回2个日期之间的周末日期列表

时间:2016-03-21 10:37:28

标签: c# datetime

目前我有这个代码返回两个日期之间所有日期的表格。我怎么能改变这个让它只返回周末日期。 这样做的目的是使用周末日期来检查DataGridView中的列标题为"灰色"周末。我希望这很清楚。

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

3 个答案:

答案 0 :(得分:8)

使用DateTime.DayOfWeek属性。

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;

答案 1 :(得分:3)

你可以创建一系列日期,然后使用DayOfWeek过滤它们,因为@Vitor说:

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

答案 2 :(得分:3)

希望此解决方案能够帮助您

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

在上面的代码中,我发现2011年3月1日至今的周六和周日。所以我采用了两个名为startDate和endDate的变量。在那之后我有他们之间的差异然后通过for循环我检查星期几是星期六或星期日

相关问题