获取开始日期,结束日期和星期几的日期

时间:2016-06-17 10:15:05

标签: c# datetime

给定开始日期(DateTime),结束日期(DateTime)和DayOfWeek列表。如何获得所有匹配日期:

示例:

StartDate : "06/17/2016" 
EndDate : "06/30/2016" 
DayOfWeek(s) : [0(Monday), 1(Tuesday), 4(Friday)]

想要的结果是:

Dates = ["06/17/2016", "06/20/2016", "06/21/2016", "06/24/2016", "06/27/2016", "06/28/2016"]

2 个答案:

答案 0 :(得分:2)

这将返回startDate和EndDate之间所有日期的列表,这些日期属于dayOfWeek的给定枚举:

var allDays = Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
var Dates = allDays.Where(dt => dayOfWeek.Contains(dt.DayOfWeek)).ToList();

答案 1 :(得分:1)

另一种可能的解决方案,我认为这很容易理解和调试,即使它比其他可能的解决方案花费更多的线路和更多的资源:

    var startDate = new DateTime(2016, 06, 17);
    var endDate = new DateTime(2016, 06, 30);

    DayOfWeek[] daysOfWeek = { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Friday };

    List<DateTime> dates = new List<DateTime>();
    if (endDate >= startDate)
    {
        var tmp = startDate;
        tmp = tmp.AddDays(1); //I notice you didn't add 06/17/2016 that is friday, if you want to add it, just remove this line
        do
        {
            if (daysOfWeek.Contains(tmp.DayOfWeek))
                dates.Add(tmp);
            tmp = tmp.AddDays(1);
        }
        while (tmp <= endDate); //If you don't want to consider endDate just change this line into while (tmp < endDate); 
    }