我正在尝试使用以下代码获得所有工作日。
private List<DateTime> getWeekDays(DateTime dt)
{
List<DateTime> result = new List<DateTime>();
int month = dt.Month;
dt = dt.AddDays(-dt.Day + 1);//Sets dt to first day of month
//Sets dt to the first week day of the month;
if (dt.DayOfWeek != DayOfWeek.Monday)
while (dt.DayOfWeek != DayOfWeek.Friday)
dt = dt.AddDays(1);
//Adds the week day and stops when next month is reached.
while (dt.Month == month)
{
result.Add(dt);
dt = dt.AddDays(dt.DayOfWeek == DayOfWeek.Friday ? 3 : 1);
}
return result;
}
但这不能正常工作。当我将July
月份传递给getWeekDays(DateTime dt)
方法时,这会正确给出所有工作日。但如果我通过August
or Semptember
,上面的代码不会返回给定月份的所有工作日。
错误在哪里?