简体   繁体   English

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

[英]Get dates given a start date an end date and day of week

Given a start date (DateTime), an end date (DateTime) and a list of DayOfWeek(s). 给定开始日期(DateTime),结束日期(DateTime)和DayOfWeek列表。 How to get all the matching dates : 如何获得所有匹配的日期:

Example : 范例:

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

The wanted result is : 想要的结果是:

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

This will return you list of all dates between the startDate and EndDate, that belong to the given enum of dayOfWeek: 这将返回您在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();

yet another possible solution, I think this is simple to understand and debug, even if it cost more lines and maybe little more resources than other possible solutions: 还有另一种可能的解决方案,我认为这很容易理解和调试,即使它比其他可能的解决方案花费更多的行和更少的资源:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM