加入工作日迄今为止要考虑到周末和节假日 [英] adding workdays to date taking into account weekends and holidays

查看:197
本文介绍了加入工作日迄今为止要考虑到周末和节假日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个日期,和节假日列表,我怎么个工作日内给定数量添加到该日期?有很多的解决方案,以更小的问题,这没有考虑节假日的(参见例如添加天,以一个日期,但不包括周末的)。

given a date, and a list of holidays, how do i add the given number of workdays to this date? there are a lot of solutions to the smaller problem which does not take account of holidays (see for example Adding Days to a Date but Excluding Weekends).

编辑:我在寻找一个O(1),或至少是线性的(在节假日的数量)解决方案

i am looking for a O(1) or at least linear (on the number of holidays) solution.

请帮忙 谢谢 康斯坦丁

please help thanks konstantin

推荐答案

接近O(1)(不初始化时间)

如果你真的想要一个O(1)解决方案,我希望你不要考虑初始化FASE。

If you really want an O(1) solution, I hope you do not take into account the initialization fase.

要初始化:

  • 内建可查询范围内的所有日期是有效的返回值排序列表。 (使用类似code从里克·加纳答案)
  • 在构建哈希表与日期从上面的列表,日期为重点,指数在列表中值

初​​始化code,你只需要一次,您缓存的结果。

The initialization code, you need only once, and you cache the result.

要查询/计算

 List<DateTime> validWorkdays = // ;
 Dictionary<DateTime, int> lookupIndexOfValidWorkday = // ;

 DateTime AddWorkdays(DateTime start, int count) {
    var startIndex = lookupIndexOfValidWorkday[start];
    return validWorkDays[startIndex + count];
 }

关于从字典检索:

获取或设置该属性的值接近一个O(1)操作。

Getting or setting the value of this property approaches an O(1) operation.

O(n)的假期数量

根据这一假期的列表进行排序,从最旧到最新的假设。 (<一href="http://stackoverflow.com/questions/279296/adding-days-to-a-date-but-excluding-weekends/279370#279370">Credits平日公式)

Under the assumption that the list of holidays is sorted from oldest to newest. (Credits for weekdays formula)

DateTime AddBusinessDay(DateTime start, int count, IEnumerable<DateTime> holidays) {
   int daysToAdd = count + ((count/ 5) * 2) + ((((int)start.DayOfWeek + (count % 5)) >= 5) ? 2 : 0);
   var end = start.AddDays(daysToAdd);
   foreach(var dt in holidays) {
     if (dt >= start && dt <= end) {
        end = end.AddDays(1);
        if (end.DayOfWeek == DayOfWeek.Saterday) {
          end = end.AddDays(2);
        }
     }
   }
   return end;
}    

此方法可以被优化。

这是很难创建一个只计算结果,就像您链接到的问题的答案,一个简单的公式。因为当你调整假期,你需要考虑到新的假期,可能落入你的范围。在周末,你知道它们之间有一个固定的间隔。

It's very hard to create a simple formula that just calculates the result, like the answers in the question you linked to. Because when you adjust for holidays you need to take into account new holidays that might fall into your range. For weekends, you know there is a fixed interval between them.

这篇关于加入工作日迄今为止要考虑到周末和节假日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆