我有一个日期集合,这些日期是工作日,并且我有一个开始日期。当我向开始日期DateTime
添加TimeSpan
时,我必须确保在TimeSpan
中添加日期时,我跳过假日。对如何做到这一点有什么建议吗?
发布于 2011-03-17 09:52:20
像这样的怎么样?
public DateTime AddBusinessDays(List<DateTime> businessDays, DateTime startDate, TimeSpan span)
{
// Add the initial timespan
DateTime endDate = startDate.Add(span);
// Calculate the number of holidays by taking off the number of business days during the period
int noOfHolidays = span.Days - businessDays.Where(d => d >= startDate && d <= endDate).Count();
// Add the no. of holidays found
endDate.AddDays(noOfHolidays);
// Skip the end date if it lands on a holiday
while (businessDays.Contains(endDate))
endDate = endDate.AddDays(1);
return endDate;
}
发布于 2011-03-17 09:44:31
按原样添加timespan。完成后,迭代搜索集合中介于原始日期和新日期之间的日期。对于每一次你遇到的每一次点击,你都会在新的日期中添加另一天,并重复,直到你完成了你的日期集合。如果对数据集合进行排序,则可以对此进行优化。
发布于 2014-01-20 10:55:08
您需要考虑在任何添加的日期范围内有多少非工作日。
在20天的范围内,可能有6个非工作日。您不能仅将此天数添加到前一天,因为新的日期范围可能还包含非工作日。您必须添加天数,然后计算出添加的天数中有多少天也是假日:
下面是一些未经测试的pcode
Add Timespan to date (DateIn,timespan)
finalDateTime = (fromDate + timespan)
fromDate = DateIn.date
toDate = finalDateTime.date
repeat
iDays = GetHolidaysBetween (fromDate, toDate)
finalDateTime = (finalDateTime + iDays)
fromDate = (toDate+1)
toDate = (toDate+iDays)
until (iDays=0)
return finalDateTime
end_function
https://stackoverflow.com/questions/5337118
复制相似问题