在给定的时间内计算正常工作日
问题描述:
需要一些帮助。我需要计算一个特定日期的正常工作日,例如,在我们国家,星期一到星期五有5个正常工作日,然后在代码中,当我在计算中使用它时,我需要排除星期六和星期几。
need some help. I need to count regular working days for a given date period, for example, in our country, we have 5 regular working days monday to friday, then in code i need to exclude saturdays and sundays when I use it on my computations.
我需要一个像C#这样的算法:
I need an algorithm something like this in C#:
int GetRegularWorkingDays(DateTime startDate, DateTime endDate)
{
int nonWorkingDays = ((endDate - startDate) % 7) * 2;
return (endDate - startDate) - nonWorkingDays;
}
我知道我的草案是离开的:(提前感谢= )
I know my draft is way way off :(. Thanks in advance. =)
PS:请稍等,投票选出最佳/最快/最有效的答案。谢谢=)
答
查看代码项目的这个例子,它使用非常有效的方式,不涉及任何循环;)
Check out this example on Code Project that uses a very efficient way that doesn't involve any looping ;)
它使用这个算法:
- 以周为单位计算时间跨度的数量。叫它,W。
- 从周数扣除第一周。 W = W-1
- 将每周
的工作天数乘以周数。调用它,D。 - 在指定的时间段内查找假期。调用它,H。
- 计算第一周的天数。称为SD。
- 计算上周的天数。调用它,ED。
- 总结所有的日子。 BD = D + SD + ED H。
- Calculate the number of time span in terms of weeks. Call it, W.
- Deduct the first week from the number of weeks. W= W-1
- Multiply the number of weeks with the number of working days per week. Call it, D.
- Find out the holidays during the specified time span. Call it, H.
- Calculate the days in the first week. Call it, SD.
- Calculate the days in the last week. Call it, ED.
- Sum up all the days. BD = D + SD + ED � H.