如何在跳过周末和其他假日的情况下向日期添加多个日期 [英] How to add a number of days to a Date while skipping weekends and other holidays

查看:714
本文介绍了如何在跳过周末和其他假日的情况下向日期添加多个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定日期。

List <DateTime> holidays = new List<DateTime>()
{
     new DateTime(2012, 01, 03),
     new DateTime(2012, 01, 26)
}; 

dateTimeReview.Value = CalculateFutureDate(dateTimeStart.Value, 7,holidays);

static DateTime CalculateFutureDate(DateTime fromDate, int numberofWorkDays, ICollection<DateTime> holidays)
{
     var futureDate = fromDate;

     for (var i = 0; i < numberofWorkDays; i++ )
     {
          if (futureDate.DayOfWeek == DayOfWeek.Saturday 
             || futureDate.DayOfWeek == DayOfWeek.Sunday
             || (holidays != null && holidays.Contains(futureDate)))
          {
              futureDate = futureDate.AddDays(1); // Increase FutureDate by one because of condition
              futureDate = futureDate.AddDays(1); // Add a working day
          }
     }
     return futureDate;
}


推荐答案

需要创建自己的假日列表。每个国家/地区的节假日都有所不同,并受到其他因素的影响。

To skip holidays you will first need to create your own list of holidays. Holidays are different in every country and also subject to other factors.

然后,您应该在循环中逐一添加天数,并检查添加的日期是否不是周末

Then you should add days one by one in a loop with a check if the added day is not a weekend day and does not occur in the list of holidays, until the given number of days has been added.

不幸的是,没有更简单的方法来完成这一操作。

Unfortunately, there is no easier way to do this.

这篇关于如何在跳过周末和其他假日的情况下向日期添加多个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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