How to calculate Number of 'Working days' between two dates in Javascript using moment.js?

前端 未结 7 2052
我寻月下人不归
我寻月下人不归 2020-12-31 05:21

How to calculate the number of working days between two dates in JavaScript using moment.js. I have a working formula that calculate these days, but the formula does not sat

7条回答
  •  情书的邮戳
    2020-12-31 05:55

    I use a simple function to accomplish that. Maybe is not the most efficient but it works. It doesn't require Moment.js. it's just Javascript.

    function getNumWorkDays(startDate, endDate) {
        var numWorkDays = 0;
        var currentDate = new Date(startDate);
        while (currentDate <= endDate) {
            // Skips Sunday and Saturday
            if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) {
                numWorkDays++;
            }
            currentDate = currentDate.addDays(1);
        }
        return numWorkDays;
    }
    

    To addDays, I use the following function:

    Date.prototype.addDays = function (days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    };
    

提交回复
热议问题