这里是您问题的简短解决方案
DateTime startDate = new DateTime(2017, 05, 1);
DateTime endDate = new DateTime(2017, 07, 21);
Dictionary<int, string> DictionOfDates = new Dictionary<int, string>();
int weekNoCount = 3; //Every 3rd week
TimeSpan tsdiff = endDate - startDate;
int days = tsdiff.Days; //total #days in the difference from start to end
for (var i = 0; i <= days; i++)
{
var date = startDate.AddDays(i);
switch (date.DayOfWeek)
{
case DayOfWeek.Monday:
DictionOfDates.Add(i, date.ToShortDateString());
break;
}
}
foreach (var item in DictionOfDates)
{
if (item.Key % weekNoCount == 0) //Check remainder is zero when divided by weekCount
MessageBox.Show(item.Value); //prints the date which you want after the n'th week check
}
我想这里的一切都是不言自明的,但如果你有任何困惑,请发表评论。
编辑 1:只是解释我使用的概念:
计算两个给定日期之间的所有天数 > 这是我们的最终计数器
现在将一天增加到startDate,同时检查日期是否在给定的一天,比如说星期一(我用@ 987654325@ 案例)。如果是,则将date 添加到字典中,并将loop #no 作为索引 以供以后使用。循环直到我们碰到counter。
-
现在对于我们在Dictionary 中的所有条目,如果 index 可以被给定的第 n 个周检查数整除,则获取日期。
就是这样!
编辑 2:围绕它创建一个方法,像这样
private void Form1_Load(object sender, EventArgs e)
{
DateTime startDate = new DateTime(2017, 05, 1);
DateTime endDate = new DateTime(2017, 07, 21);
int weekNoCount = 3; //Every 3rd week
DayOfWeek[] days = new DayOfWeek[2] { DayOfWeek.Monday, DayOfWeek.Thursday }; //Pass required days here
FetchTheDays(startDate, endDate, weekNoCount, days);
}
private void FetchTheDays(DateTime startDate, DateTime endDate, int weekNoCount, DayOfWeek[] daysofWeek)
{
Dictionary<int, DateTime> DictionOfDates = new Dictionary<int, DateTime>();
TimeSpan tsdiff = endDate - startDate;
int days = tsdiff.Days; //total #days in the difference from start to end
for (var i = 0; i <= days; i++)
{
var date = startDate.AddDays(i);
foreach (var weekday in daysofWeek)
{
if (date.DayOfWeek == weekday)
DictionOfDates.Add(i, date);
}
}
string testExample = "";
foreach (var item in DictionOfDates)
{
if (item.Key % weekNoCount == 0) //Check remainder is zero when divided by weekCount
testExample += (item.Value.ToShortDateString() + " (" + item.Value.DayOfWeek + ")" + "\n");
}
MessageBox.Show(testExample);
}
输出:
希望你现在已经明白了