C#日期时间为加/减工作日 [英] c# DateTime to Add/Subtract Working Days
本文介绍了C#日期时间为加/减工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里给出一个日期方案(的DateTime
),该日期加/减 X
天(实现与 DateTime.AddDays
)必须加上或减去 X
工作日,即跳过周末和节假日。我怎样才能得到它这样做呢?我要实现自己的版本,并将其连接到一个日历或东西吗?
I have a scenario where given a date(DateTime
),that date plus/minus x
days(achieved with DateTime.AddDays
) must add or subtract x
working days, i.e., skip weekends and holidays. How can I get it to do this? Should I implement my own version and attach it to a calendar or something?
推荐答案
我会建议你必须自己实现它,并会做这样的扩展方法中:
I would suggest that you have to implement it by your own, and would do it inside an extension method like this:
public static class DateTimeExtensions
{
public static DateTime AddWorkdays(this DateTime originalDate, int workDays)
{
DateTime tmpDate = originalDate;
while (workDays > 0)
{
tmpDate = tmpDate.AddDays(1);
if (tmpDate.DayOfWeek < DayOfWeek.Saturday &&
tmpDate.DayOfWeek > DayOfWeek.Sunday &&
!tmpDate.IsHoliday())
workDays--;
}
return tmpDate;
}
public static bool IsHoliday(this DateTime originalDate)
{
// INSERT YOUR HOlIDAY-CODE HERE!
return false;
}
}
这篇关于C#日期时间为加/减工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文