如何使用Moment JS计算范围之间给定工作日的数量?
如何使用Moment JS和jQuery查找给定工作日(例如:星期二)中有多少日期范围?
我可以找到使用差异的天数: http : //momentjs.com/docs/#/displaying/difference/
我知道开始和结束日期,所以我觉得应该可以吗?
例如:3月1日到3月25日之间有多少个星期二?
我想出了以下函数,它似乎适用于我尝试的一些测试用例:
function weekdaysBetween(d1, d2, isoWeekday) { // ensure we have valid moment instances d1 = moment(d1); d2 = moment(d2); // figure out how many days to advance to get to the next // specified weekday (might be 0 if d1 is already the // specified weekday). var daysToAdd = ((7 + isoWeekday) - d1.isoWeekday()) % 7; var nextTuesday = d1.clone().add(daysToAdd, 'days'); // if we are already passed the end date, there must not // be any of that day in the given period. if (nextTuesday.isAfter(d2)) { return 0; } // otherwise, just return the whole number of weeks // difference plus one for the day we already advanced to var weeksBetween = d2.diff(nextTuesday, 'weeks'); return weeksBetween + 1; }
您传递isoWeekday
值为您想要计算的那一天。 例如,星期二,传递2
。
示例调用:
var d1 = moment('2015-03-01'); var d2 = moment('2015-03-25'); console.log('result:', weekdaysBetween(d1, d2, 2)); // => result: 4
Wolfram Alpha给出了相同的结果 。
但是,在完全信任之前,您应该添加自己的测试。
如果您想要找到两个日期N和M之间的工作日W (例如星期一,星期二……),您可以:
- 在N之后找到W的下一个出现N’ 。
- 找出N’和M之间的天数。
- 如果N’在M之后,则之间没有W. 否则, W天数应为1 + floor((MN)/ 7) 。
function getWeekdaysBetweenDates(firstDate, secondDate, dayOfWeek) { var MILISECONDS_IN_DAY = 86400000; function getNextDayOfWeek(date, dayOfWeek) { date.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7); return date; } firstDate = getNextDayOfWeek(firstDate, dayOfWeek); if (firstDate > secondDate) { return 0; } return 1 + Math.floor(((secondDate - firstDate) / MILISECONDS_IN_DAY) / 7); } var firstDate = new Date("March 1, 2015"); var secondDate = new Date("March 25, 2015"); console.log(getWeekdaysBetweenDates(firstDate, secondDate, 2)); // 4
https://github.com/andruhon/moment-weekday-calc做你需要的。 它计算范围内的特定工作日,并选择排除特定日期(例如公共假日)
用法:
moment().isoWeekdayCalc({ rangeStart: '1 Apr 2015', rangeEnd: '31 Mar 2016', weekdays: [1,2,3,4,5], //weekdays Mon to Fri exclusions: ['6 Apr 2015','7 Apr 2015'] //public holidays }) //returns 260 (260 workdays excluding two public holidays)
如果你像我一样,对数学感到困惑:
var startDate = moment().startOf('month'); var endDate = moment().endOf('month'); var aDate = moment(startDate).day('Sunday'); var weekDays = 0; while (aDate.isSameOrBefore(endDate)) { if (aDate.isSameOrAfter(startDate) && aDate.isSameOrBefore(endDate)) weekDays++; aWeekDayDate.add(1, 'week'); }