本文介绍了JS假期除外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对javascript和moment.js很陌生.我正在一个网站上,我们需要在该网站上列出产品的下5个可能的提货日期,但不包括周末和节假日.我使用从网上找到的功能对此进行了了解.在跳过周末时效果很好,但是我不能让假期工作.任何帮助,将不胜感激. http://jsfiddle.net/rLjQx/940/

I'm very new to javascript and moment.js. I'm working on a site where we need to list out the next 5 possible pickup dates for a product, excluding weekends and holidays. I have a start on this, using a function I found online. It works well at skipping the weekends, however I can't get the holidays working. Any help would be appreciated. http://jsfiddle.net/rLjQx/940/

moment.fn.addWorkdays = function(days) {
  var increment = days / Math.abs(days);
  var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
  var remaining = days % 5;
  while (remaining != 0) {
    date.add(increment, 'days');
    // Check for weekends and a static date
    if (!(date.isoWeekday() === 6) && !(date.isoWeekday() === 7) && !(date.date() === 1 && date.month() === 4)) {
      remaining -= increment;
    }
  }
  return date;
};

for (count = 0; count < 5; count++) {
  var test = moment().addWorkdays(count + 1).format('dddd, MMMM Do YYYY');
  document.write("Pickup date : " + test);
  document.write("<br />");
}

推荐答案

这是使用我的 moment-holiday 插件. :)

Here's a quick and easy solution using my moment-holiday plugin. :)

function getNextWorkDays(count, format) {
    if (!count) { count = 5; }
    if (!format) { format = 'dddd, MMMM Do YYYY'; }

    var days = [];
    var d = moment().startOf('day');
  
    for (i = 0; i < count; i++) {
      d.add(1, 'day');
  
      if (d.day() === 0 || d.day() === 6 || d.isHoliday()) {
        count++;
        continue;
      }
    
      days.push(moment(d).format(format));
    }
  
  return days;
}

var days = getNextWorkDays();

alert("The following days are available for pickup:\n\n" + days.join("\n"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdn.rawgit.com/kodie/moment-holiday/v1.2.0/moment-holiday.js"></script>

这篇关于JS假期除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 03:23