C# 输入一个时间段 判断 该时间段内工作日天数 (排除节假日)
如输入2013-08-01至2013-08-05这期间的工作天数去掉周六周日工作了3天当然输入的时间段不确定各位帮帮忙先谢了。详细点啊C#的...
如 输入2013-08-01 至 2013-08-05 这期间的工作天数 去掉周六周日 工作了3天
当然 输入的时间段不确定 各位帮帮忙 先谢了。
详细点啊 C# 的 展开
当然 输入的时间段不确定 各位帮帮忙 先谢了。
详细点啊 C# 的 展开
1个回答
展开全部
写好了,用一个扩展方法实现,具体参考了国外一个论坛上的答案,但是我作了一些调整,感谢原作者Alexander!以下是截图和核心代码,完整的源码在附件中,如有疑问欢迎追问。
注意:原方法写得非常好,你可以指定国定假日,但是在实例源码中我并没有用,你自己注意看一下。
核心代码:
// -----------------------------------------------------------------------
// <copyright file="DateTimeExtention.cs" Author="不识台北路">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------
namespace WorkingDays
{
using System;
/// <summary>
/// TODO: Update summary.
/// </summary>
public static class DateTimeExtention
{
/// <summary>
/// Calculates number of business days, taking into account:
/// - weekends (Saturdays and Sundays)
/// - bank holidays in the middle of the week
/// </summary>
/// <param name="firstDay">First day in the time interval</param>
/// <param name="lastDay">Last day in the time interval</param>
/// <param name="bankHolidays">List of bank holidays excluding weekends</param>
/// <returns>Number of business days during the 'span'</returns>
public static int BusinessDaysUntil(this DateTime firstDay, DateTime lastDay, params DateTime[] bankHolidays)
{
firstDay = firstDay.Date;
lastDay = lastDay.Date;
if (firstDay > lastDay)
throw new ArgumentException("Incorrect last day " + lastDay);
TimeSpan span = lastDay - firstDay;
int businessDays = span.Days + 1;
int fullWeekCount = businessDays / 7;
// find out if there are weekends during the time exceedng the full weeks
if (businessDays > fullWeekCount * 7)
{
// we are here to find out if there is a 1-day or 2-days weekend
// in the time interval remaining after subtracting the complete weeks
int firstDayOfWeek = firstDay.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)firstDay.DayOfWeek;
int lastDayOfWeek = lastDay.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)lastDay.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
if (firstDayOfWeek <= 6)
{
if (lastDayOfWeek >= 7)// Both Saturday and Sunday are in the remaining time interval
businessDays -= 2;
else if (lastDayOfWeek >= 6)// Only Saturday is in the remaining time interval
businessDays -= 1;
}
else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)// Only Sunday is in the remaining time interval
businessDays -= 1;
}
// subtract the weekends during the full weeks in the interval
businessDays -= fullWeekCount + fullWeekCount;
// subtract the number of bank holidays during the time interval
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (firstDay <= bh && bh <= lastDay)
--businessDays;
}
return businessDays;
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询