如何获取所选日期范围内的所选星期几的日期

时间:2018-10-24 14:20:01

标签: c# datetime

如何获取所选星期的日期,该日期在C#中的所选日期范围中。

我是C#的新手,请帮助我将这些日期保存在日期范围内的数据库中

2 个答案:

答案 0 :(得分:0)

您可以在范围之间输入所有可能的日期,然后对照DaysOfWeeks列表进行检查:

using System;
using System.Collections.Generic;


public class Program
{
    public static void Main()
    {
        var selectedDayOfWeeks = new List<DayOfWeek>{DayOfWeek.Thursday, DayOfWeek.Saturday};
        var startDate = new DateTime(2017, 10, 24);
        var endDate = new DateTime(2017, 10, 28);

        var possibleDates = new List<DateTime>();
        for(var current = startDate; current <= endDate; current= current.AddDays(1))
        {
            if(selectedDayOfWeeks.Contains(current.DayOfWeek))
            {
                possibleDates.Add(current);
            }
        }

        foreach(var d in possibleDates){
            Console.WriteLine(d);
        }

    }
}

答案 1 :(得分:0)

这是一种方法...

        var from = DateTime.Parse("10/24/2018");
        var to = DateTime.Parse("11/14/2018");
        var dayList = new List<DateTime>();

        for (var day = from.Date; day.Date <= to.Date; day = day.AddDays(1))
        {
            if
            (
                day.DayOfWeek == DayOfWeek.Monday ||
                day.DayOfWeek == DayOfWeek.Wednesday ||
                day.DayOfWeek == DayOfWeek.Friday ||
                day.DayOfWeek == DayOfWeek.Sunday
            )
            {
                dayList.Add(day);
            }
        }

DayOfWeek是系统名称空间中的枚举,您可以确定您的“星期几”复选框,并将相应的枚举值添加到DayOfWeek列表中,并按Kevin Smith的说明使用

        var selectedDaysOfWeek = new List<DayOfWeek>();
        var from = DateTime.Parse("10/24/2018");
        var to = DateTime.Parse("11/14/2018");
        var dayList = new List<DateTime>();

        if (checkBoxMonday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Monday); }
        if (checkBoxTuesday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Tuesday); }
        if (checkBoxWednesday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Wednesday); }
        if (checkBoxThursday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Thursday); }
        if (checkBoxFriday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Friday); }
        if (checkBoxSaturday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Saturday); }
        if (checkBoxSunday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Sunday); }

        for (var day = from.Date; day.Date <= to.Date; day = day.AddDays(1))
        {
            if (selectedDaysOfWeek.Contains(day.DayOfWeek))
            {
                dayList.Add(day);
            }
        }

        foreach(var day in dayList)
        {
            // Add to day to DB
        }