【问题标题】:Add no. of days in a date to get next date(excluding weekends)加号。获得下一个日期的日期中的天数(不包括周末)
【发布时间】:2011-12-09 20:15:48
【问题描述】:

我有一个约会,我需要添加没有。获得未来日期的天数,但应排除周末。 即

input date = "9-DEC-2011";
No. of days to add  = '13';

next date should be "28-Dec-2011"

这里不计算周末(周六/周日)。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

试试这个

var startDate = "9-DEC-2011";
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "", noOfDaysToAdd = 13, count = 0;
while(count < noOfDaysToAdd){
    endDate = new Date(startDate.setDate(startDate.getDate() + 1));
    if(endDate.getDay() != 0 && endDate.getDay() != 6){
       //Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
       count++;
    }
}
alert(endDate);//You can format this date as per your requirement

工作Demo

【讨论】:

  • @Nishu - 你有机会看看这个吗?
  • 感谢 Shanker...是的,我做到了....我也实现了这个逻辑,但主要关注的是优化逻辑。因为如果没有。天数就像 30,40,50 等等......,循环将执行那个没有。的时候,你有什么优化的解决方案吗??
  • 我认为我们可以对此进行优化,让我有时间尝试一下。
  • @ShankarSangoli 谢谢你为我做的这项工作。但是我有自定义周末,比如 1 月 26 日的国定假日,我想排除那也有任何解决方案
  • 可以说我需要在 startDate 上增加几周或几个月,那么我们该怎么做呢?考虑到一个月可以是 28、29、30 或 31 天这一事实。
【解决方案2】:

@ShankarSangoli

这是一个较新的版本,它避免在每个循环中重新创建 Date 对象,请注意它现在被包装在一个函数中。

function calcWorkingDays(fromDate, days) {
    var count = 0;
    while (count < days) {
        fromDate.setDate(fromDate.getDate() + 1);
        if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
            count++;
    }
    return fromDate;
}
alert(calcWorkingDays(new Date("9/DEC/2011"), 13));

【讨论】:

    【解决方案3】:

    这是一个没有任何循环或外部库的优雅解决方案:

    function addBusinessDaysToDate(date, days) {
      var day = date.getDay();
    
      date = new Date(date.getTime());
      date.setDate(date.getDate() + days + (day === 6 ? 2 : +!day) + (Math.floor((days - 1 + (day % 6 || 1)) / 5) * 2));
      return date;
    }
    
    var date = "9-DEC-2011";
    var newDate = addBusinessDaysToDate(new Date(date.replace(/-/g, "/")), 13);
    console.log(newDate.toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/, '$2-$1-$3')); // alerts "28-Dec-2011"

    【讨论】:

    • 这是一个很好的解决方案。即使开始日期是周六或周日,它也有效。
    【解决方案4】:

    或者你也可以这样

    function addWeekdays(date, weekdays) {
        var newDate = new Date(date.getTime());
        var i = 0;
        while (i < weekdays) {
            newDate.setDate(newDate.getDate() + 1);
            var day = newDate.getDay();
            if (day > 1 && day < 7) {
                i++;
            }
        }
        return newDate;
    }
    var currentDate = new Date('10/31/2014');
    var targetDate = addWeekdays(currentDate, 45);
    alert(targetDate);
    

    【讨论】:

      【解决方案5】:

      使用moment.js

      const DATE_FORMAT = 'D-MMM-YYYY';
      const SUNDAY = 0; // moment day index
      const SATURDAY = 6; // moment day index
      const WEEKENDS = [SATURDAY, SUNDAY];
      
      function addBusinessDays(stringDate, numberOfDays, dateFormat = DATE_FORMAT) {
        const date = moment(stringDate, dateFormat);
          
        let count = 0;
              
        while (count < numberOfDays) {
          date.add(1, 'day');
      
          // Skip weekends
          if (WEEKENDS.includes(date.day())) {
            continue;
          }
      
          // Increment count
          count++;
        }
          
        return date.format(dateFormat);
      }
      
      // Test cases
      console.log(addBusinessDays('3-Mar-2021', 1)); // 4-Mar-2021
      console.log(addBusinessDays('3-Mar-2021', 2)); // 5-Mar-2021
      console.log(addBusinessDays('3-Mar-2021', 3)); // 8-Mar-2021
      console.log(addBusinessDays('3-Mar-2021', 4)); // 9-Mar-2021
      console.log(addBusinessDays('3-Mar-2021', 5)); // 10-Mar-2021
      console.log(addBusinessDays('9-Dec-2011', 13)); // 28-Dec-2011
      console.log(addBusinessDays('10-Dec-2011', 13)); // 28-Dec-2011 (Saturday, so remain on Friday)
      console.log(addBusinessDays('11-Dec-2011', 13)); // 28-Dec-2011 (Sunday, so remain on Friday)
      console.log(addBusinessDays('12-Dec-2011', 13)); // 29-Dec-2011
      console.log(addBusinessDays('13-Dec-2011', 13)); // 30-Dec-2011
      console.log(addBusinessDays('14-Dec-2011', 13)); // 2-Jan-2012
      &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"&gt;&lt;/script&gt;

      【讨论】:

      • 我认为这可以返回一个周末为 numberOfDays
      • 你是对的@Matt!我在这个 coden-p 中添加了额外的处理
      【解决方案6】:

      这个问题已经很老了,但是以前的所有答案都在一天一个地迭代。这可能会在很多天里效率低下。这对我有用,假设 days 是一个正整数并且 startDate 是一个工作日:

      function addWorkingDates(startDate, days) {
        const current_day = startDate.getDay() - 1; // Week day, starting on Monday
        const weekend_days = 2 * parseInt((current_day + days) / 5);
        startDate.setDate(changed_to.getDate() + days + weekend_days);
      }
      
      addWorkingDates(new Date(),5)

      【讨论】:

        【解决方案7】:

        出于某种原因,递归地尝试这个对我来说更直观。此版本不考虑节假日,但您可以更改 isValid 函数以检查任何内容。

        function addWeekdaysToDate(date, numberToAdd) {
          var isValid = function(d) { return d.getDay() !== 0 && d.getDay() !== 6 }
          if(Math.abs(numberToAdd) > 1) {
            return addWeekdaysToDate(
              addWeekdaysToDate(date, Math.sign(numberToAdd)),
              numberToAdd - Math.sign(numberToAdd)
            )
          } else if(Math.abs(numberToAdd) === 1) {
            var result = new Date(date)
            result.setDate(result.getDate() + Math.sign(numberToAdd))
            if(isValid(result)) {
              return result
            } else {
              return addWeekdaysToDate(result, Math.sign(numberToAdd))
            }
          } else if(numberToAdd === 0) {
            return date
          }
          return false
        }
        
        console.log(addWeekdaysToDate(new Date(), 1))
        console.log(addWeekdaysToDate(new Date(), 5))
        console.log(addWeekdaysToDate(new Date(), -7))

        certain browsers 中,您可能需要为Math.sign 使用polyfill:

        Math.sign = Math.sign || function(x) {
          x = +x; // convert to a number
          if (x === 0 || isNaN(x)) {
            return Number(x);
          }
          return x > 0 ? 1 : -1;
        }
        

        【讨论】:

          【解决方案8】:

          试试这个解决方案

          <script language="javascript">
          
          function getDateExcludeWeekends(startDay, startMonth, startYear, daysToAdd) {
          var sdate = new Date();
          var edate = new Date();
          var dayMilliseconds = 1000 * 60 * 60 * 24;
          sdate.setFullYear(startYear,startMonth,startDay);
          edate.setFullYear(startYear,startMonth,startDay+daysToAdd);
          var weekendDays = 0;
          while (sdate <= edate) {
              var day = sdate.getDay()
              if (day == 0 || day == 6) {
                  weekendDays++;
              }
              sdate = new Date(+sdate + dayMilliseconds);
          } 
          sdate.setFullYear(startYear,startMonth,startDay + weekendDays+daysToAdd);
          return sdate;
          }
          
          </script>
          

          【讨论】:

            【解决方案9】:

            如果要获取下一个工作日,从特定日期开始,请使用以下代码...

            function getNextWorkingDay(originalDate) {
                var nextWorkingDayFound = false;
                var nextWorkingDate = new Date();
                var dateCounter = 1;
            
                while (!nextWorkingDayFound) {
                    nextWorkingDate.setDate(originalDate.getDate() + dateCounter);
                    dateCounter++;
            
                    if (!isDateOnWeekend(nextWorkingDate)) {
                        nextWorkingDayFound = true;
                    } 
                }
            
                return nextWorkingDate;
            }
            
            function isDateOnWeekend(date) {
                if (date.getDay() === 6 || date.getDay() === 0)
                    return true;
                else
                    return false;
            }
            

            【讨论】:

              【解决方案10】:

              试试这个

              function calculate() {
                var noOfDaysToAdd = 13;
                var startDate = "9-DEC-2011";
                startDate = new Date(startDate.replace(/-/g, "/"));
                var endDate = "";
                count = 0;
                while (count < noOfDaysToAdd) {
                  endDate = new Date(startDate.setDate(startDate.getDate() + 1));
                  if (endDate.getDay() != 0 && endDate.getDay() != 6) {
                    count++;
                  }
                }
                document.getElementById("result").innerHTML = endDate;
              }
              <div>
                Date of book delivery: <span id="result"></span><br /><br />
                <input type="button" onclick="calculate();" value="Calculate" />
                <br>
                <br>
              </div>

              【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-04-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-04-15
              相关资源
              最近更新 更多