使用Moment JS获取两个日期之间的工作日

时间:2013-09-08 19:17:16

标签: javascript momentjs

有没有办法通过MomentJS获得两个日期之间的工作日?工作日是没有周末,周一,周二,周三,周四和周五的一周。到目前为止,我尝试使用diff()方法(http://momentjs.com/docs/#/displaying/difference/),如下所示:

var daysElapsed = today.diff(past, 'days');

据我所知,diff()仅适用于提供所有两个日期之间的日期,包括周末日。谢谢你的时间!

4 个答案:

答案 0 :(得分:2)

您需要为此编写自己的函数。

由于您知道确切的开始和结束日期,因此并不难。

  1. 获取开始日期和结束日期的一周中的哪一天。
  2. 只计算两者之间的工作日。
  3. 我认为这将是非常直接的实施。

答案 1 :(得分:2)

let start = moment(startDate, 'YYYY-MM-DD'); //Pick any format
let end = moment(); //right now (or define an end date yourself)
let weekdayCounter = 0;  

while (start <= end) {
 if (start.format('ddd') !== 'Sat' && start.format('ddd') !== 'Sun'){
   weekdayCounter++; //add 1 to your counter if its not a weekend day
 }
 start = moment(start, 'YYYY-MM-DD').add(1, 'days'); //increment by one day
}
console.log(weekdayCounter); //display your total elapsed weekdays in the console!

答案 2 :(得分:0)

虽然这个问题已经很老了,但我已经偶然发现了它并且找不到我正在寻找的真正答案。

我希望这个解决方案对其他人也有帮助:

const momentStart = moment(initialDate);
const momentFinal = moment(finalDate);

// Get the diff in days between both dates
const diff = momentFinal.diff(momentStart, "days");

// If diff is 7 or bigger, all days are included
if (diff >= 7) {
  return moment.weekdays();
}

// Need to calculate, check which day we start from
const firstDay = momentStart.day();
const weekdaysBetween = [];

// For each diff day, we get the next one)
for (let i = 0; i <= diff; i++) {
  // use % to loop to beginning again (e.g: start at friday and have +4)
  weekdaysBetween.push(moment.weekdays((firstDay + i) % 7));
}

return weekdaysBetween;

您还可以检查 working demo version here

答案 3 :(得分:-2)

Refer this

以下是您的要求的解决方案