最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Moment JS Excluding Holidays - Stack Overflow

programmeradmin5浏览0评论

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. /

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 />");
}

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/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 />");
}
Share Improve this question asked Apr 26, 2017 at 20:31 Matt PalmerMatt Palmer 411 gold badge1 silver badge2 bronze badges 1
  • 2 Holidays plugin for Moment.JS - gist.github./jrhames/5200024 :) hope this helps – LatentDenis Commented Apr 26, 2017 at 20:34
Add a ment  | 

2 Answers 2

Reset to default 4

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./ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdn.rawgit./kodie/moment-holiday/v1.2.0/moment-holiday.js"></script>

I know this is an old post, but now that moment is deprecated using built-in date methods is a much better approach. Here is a gist I created doing just that and is copied below for reference.

function isHoliday(date: Date) {
  const holidays = {
    MD: {
      // Month, Day
      '1/1': "New Year's Day",
      '7/4': 'Independence Day',
      '11/11': "Veteran's Day",
      '12/25': 'Christmas Day',
      '12/31': "New Year's Eve"
    },
    MODW: {
      // Month, Occurence, Day of Week
      '1/3/1': 'Martin Luther King Jr. Day',
      '2/3/1': 'Presidents Day',
      '5/L/1': 'Memorial Day',
      '9/1/1': 'Labor Day',
      '10/2/1': 'Columbus Day',
      '11/4/4': 'Thanksgiving Day'
    }
  };
  const dayOfTheMonth = date.getDate();
  const month = date.getMonth() + 1;
  const dayOfTheWeek = date.getDay(); // 0 - 6, Su -> Sa
  const lastDayOfTheMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  const isLastOccurrence = dayOfTheMonth + 7 > lastDayOfTheMonth;
  let currentOccurrenceDay = dayOfTheMonth,
    occurrence = 0;
  for (currentOccurrenceDay; currentOccurrenceDay > 0; currentOccurrenceDay -= 7) occurrence++;

  return !!(
    holidays.MD?.[`${month}/${dayOfTheMonth}`] ||
    (isLastOccurrence && holidays.MODW?.[`${month}/L/${dayOfTheWeek}`]) ||
    holidays.MODW?.[`${month}/${occurrence}/${dayOfTheWeek}`]
  );
}
发布评论

评论列表(0)

  1. 暂无评论