我必须计算C#中两个给定日期之间的工作日数量。我已经在整个互联网上进行了搜索(甚至在StackOverflow上),但找不到解决我问题的好方法...这就是我现在所拥有的:
public int WorkDays(DateTime startDate, DateTime endDate)
{
int days = 0;
while (startDate <= endDate)
{
if (startDate.DayOfWeek != DayOfWeek.Saturday && startDate.DayOfWeek != DayOfWeek.Sunday)
{
++days;
}
startDate = startDate.AddDays(1);
}
return days;
}
这是我猜应该可以进行的测试:
[TestMethod]
public void TestWorkdays()
{
var calc = new WorkDayCalculator();
Assert.AreEqual(14, calc.WorkDays(new DateTime(2012, 10, 1), new DateTime(2012, 10, 18)));
Assert.AreEqual(10, calc.WorkDays(new DateTime(2012, 10, 6), new DateTime(2012, 10, 21)));
Assert.AreEqual(12, calc.WorkDays(new DateTime(2012, 10, 5), new DateTime(2012, 10, 22)));
// over maand heen
Assert.AreEqual(5, calc.WorkDays(new DateTime(2012, 10, 29), new DateTime(2012, 11, 4)));
// over jaar heen (precies 52 weken)
Assert.AreEqual(260, calc.WorkDays(new DateTime(2011, 10, 10), new DateTime(2012, 10, 5)));
// startdatum > einddatum! (bad path)
Assert.AreEqual(-40, calc.WorkDays(new DateTime(2012, 12, 29), new DateTime(2012, 11, 4)));
}