如何使用Moment JS计算范围之间给定工作日的数量?

时间:2015-03-17 03:34:53

标签: jquery momentjs date-arithmetic

如何使用Moment JS和jQuery了解某个工作日(例如:星期二)中有多少个在日期范围内?

我可以找到使用差异的天数: http://momentjs.com/docs/#/displaying/difference/

我知道开始和结束日期,所以我觉得应该可以吗?

示例:3月1日到3月25日之间有多少个星期二?

4 个答案:

答案 0 :(得分:10)

我提出了以下函数,它似乎适用于我尝试的一些测试用例:

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 gives the same result

但是,在完全信任之前,您应该添加自己的测试。

答案 1 :(得分:3)

如果您要在 N M <两个日期之间找到工作日 W (例如星期一,星期二......)的数量/ em>,你可以:

  1. N 之后找到 W 的下一个 N&#39;
  2. 查找 N&#39; M 之间的天数。
  3. 如果 N&#39; M 之后,则 W 之间没有 W 。否则, W 天数应为1 + floor((M-N)/ 7)
  4. 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
    

答案 2 :(得分:3)

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)

答案 3 :(得分:0)

如果你像我一样有一种对数学感到困惑的头脑:

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');
}