2011-03-17 40 views
1

我有一個日期的集合是工作日,我有一個開始日期。當我將TimeSpan添加到開始日期DateTime時,我必須確保在TimeSpan中添加日期時,我跳過節假日。有關我如何做到這一點的任何建議?C#將TimeSpan添加到日期時間考慮BusinessDays

+0

你是什麼節日呢?週末?銀行假期?你去西班牙旅行? – w69rdy 2011-03-17 09:27:41

+0

我指定我有一組日期,我把它視爲工作日 – Aks 2011-03-17 09:30:05

+0

是的,你也指定你想跳過假期,但是你還沒有指定'假期'的含義? – w69rdy 2011-03-17 09:31:17

回答

-1

這樣的事情呢?

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

爲什麼downvote? – w69rdy 2014-01-20 11:41:34

0

您按照原樣添加時間段。完成之後,您將迭代搜索集合中的日期,該日期位於原始日期和新日期之間。對於每次碰到每次碰撞時,您都會在新的日期再添加一天,然後重複,直到您完成日期的收集。如果你的datecollection被排序,這可以被優化。

0

您需要考慮在任何添加的日期範圍內有多少個非營業日。

在20天的範圍內,可能有6個非營業日。 由於新的日期範圍也可能包含非營業日,因此您無法將此天數添加到最後一天。您必須添加天,然後找出如何,你已經添加了這些日子不少也是假期:

下面是一些非測試的P碼

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