开发者

C# Add TimeSpan to DateTime by considering BusinessDays

I have a collection of dates that are business days and I have a Start Date. When I add a TimeSpan to the Start Date DateTime I have to ensure that when adding the days in TimeSpan, I skip over holid开发者_JAVA百科ays. Any suggestions on how I can do this?


You add the timespan as it is. When that is done, you iterate search for dates in your collection that falls between the original date and the new date. For each time you encounter for each hit you add another day to the new date, and repeat until you are through your collection of dates. This can be optimized if your datecollection is sorted.


You need to take into account how many non-business days there are in any added date range.

In a 20 day range, there may be 6 non-business days. You can't just add this number of days to the last day because the new date range may contain non-business days too. You have to add the days, and then figure out how many of those days you've added are also holidays:

Here's some non-tested 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


What about something like this?

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜