我使用的擴展方法返回平日的量時間跨度,甚至是兩個日期之間的完整日期列表,那麼您可以針對IEnumerable運行一個lambda表達式來獲得所需的內容。下面是靜態類的一個非常基本的例子:
public static class TimeSpanextensions
{
public static IEnumerable<DateTime> GetDays(this DateTime start, DateTime end, bool returnWeekDays = false)
{
List<DateTime> daysInSpan = new List<DateTime>();
//change following line to accomodate date format if needed
TimeSpan ts = start.Date - end.Date;
if(start < end)
{
DateTime _this = start;
while (_this < end)
{
_this = start.AddDays(1);
daysInSpan.Add(_this);
}
}
if(start > end)
{
DateTime _this = start;
while(_this > end)
{
_this = _this.AddDays(-1);
daysInSpan.Add(_this);
}
}
if(returnWeekDays)
{
return daysInSpan.Where(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday);
}
return daysInSpan;
}
我用這個用下面的例子:
public static IEnumerable<DateTime> WeekDays(DateTime one, DateTime two)
{
TimeSpan test = one - two;
return one.GetDays(two, true).ToList();
}
這是一個基本的例子,一個時間跨度的日子或平日返回作爲實際工作類型,而不是TimeSpan返回的類型爲int的TimeSpan日子。因此,如果您有兩個日期StartDate和EndDate,則只需執行以下操作即可獲取TimeSpane中存在的工作日。
int count = Start < EndDate ? 1 : -1;
DateTime newDate = StartDate;
List<DateTime> allDaysList = new List<DateTime();
while(newDate != EndDate)
{
newDate = newDate.AddDays(count); //will eithr add or subtract a day
allDays.Add(newDate);
}
//now return either only weekdays days
allDays = allDays.Where(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday);
如果你只是想工作日的時間跨度計數執行以下操作:
int workDays = allDays.Where(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday).Count();
也就是說不同的方式來處理這個問題。爲了擴展這個,你只需創建一個靜態方法,除了這個作爲參數。例如:
List<DateTime> weekDaysOnly = StartsDate.GetDays(endDate).ToList();
//then once again do your business day lambda expression here to leave your list with weekdays only. Hope this helps.
可能有所幫助:http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates –
'週五-Monday' =>' 1',那麼'Friday-Saturday'和'Friday-Sunday'的結果是什麼? –
[計算C#中兩個日期之間的平日數]可能的重複(http://stackoverflow.com/questions/1820173/calculate-the-number-of-weekdays-between-two-dates-in-c-sharp ) –