我会给你开始日期和结束日期以及周一的一周
Public void check(string StartDate, string EndDate, String Monday
{
// Logic here
}
如何查找从开始日期到结束日期和日期的星期一。
答案 0 :(得分:4)
要实现您的目标,您应该传递startDate,endDate和一周中的某一天(最好不要作为字符串,而是作为DayOfWeek以获得更好的代码可读性):
public List<DateTime> GetListOfDays(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek)
{
var list = new List<DateTime>();
var daysDifference = endDate.Subtract(startDate).TotalDays;
for (int i = 0; i < daysDifference; i++)
{
var date = startDate.AddDays(i);
if (date.DayOfWeek == dayOfWeek)
{
list.Add(date);
}
}
return list;
}
返回的列表将包含其确切日期的所有星期一(如果您将Monday
作为dayOfWeek
传递)。如果在返回的列表上执行.Count()
,您可以看到返回了多少个。
答案 1 :(得分:0)
public void CountMondays(DateTime start, DateTime end){
int mondays = 0;
for(DateTime date = start;date <= end; date=date.AddDays(1)){
if(date.DateOfWeek == DayOfWeek.Monday)
mondays++;
}
return mondays;
}
答案 2 :(得分:0)
这可以工作,不需要循环。速度的差异并不大。大约100年,它的5ms,然而,2000年,它大约是60-70ms(使用上面的List排序),其中非循环始终为0。
public static int GetAmountBetween(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek)
{
int addAmount = 0;
switch (dayOfWeek)
{
case DayOfWeek.Monday:
addAmount = 0;
break;
case DayOfWeek.Tuesday:
addAmount = 1;
break;
case DayOfWeek.Wednesday:
addAmount = 2;
break;
case DayOfWeek.Thursday:
addAmount = 3;
break;
case DayOfWeek.Friday:
addAmount = 4;
break;
case DayOfWeek.Saturday:
addAmount = 5;
break;
case DayOfWeek.Sunday:
addAmount = 6;
break;
}
return (endDate.Subtract(startDate).Days + addAmount) / 7;
}