如何使用Moment.js排除两个日期之间的周末

时间:2013-12-26 17:06:34

标签: javascript jquery momentjs

我想在JavaScript代码中排除周末。我使用moment.js并且难以为'days'选择正确的变量。

到目前为止,我认为我需要通过将工作日变量更改为仅从第1天到第5天来排除第6天(星期六)和第0天(星期日)。但不确定它是如何变化的。

我的jsfiddle显示在这里:FIDDLE

HTML

<div id="myContent">
<input type="radio" value="types" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping1">Free Shipping: (<span id="fsv1" value="5">5</span> to <span id="fsv2" value="10">10</span> working days)</label> </td><br>
    <div id="contacts" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative;margin-bottom:25px;">     
    Contacts
</div>
<input type="radio" value="groups" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping2">Express Shipping: (<span id="esv1" value="3">3</span> to <span id="esv2" value="4">4</span> working days)</label> </td>    
<div id="groups" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative">     
    Groups
</div>
</div>

的JavaScript

var a = 5; //Free shipping between a
var b = 10;//and b
var c = 3;//Express shipping between c
var d = 4;//and d    
var now = moment();    
var f = "Your item will be delivered between " + now.add("days",a).format("Do MMMM") + " and " + now.add("days",b).format("Do MMMM");
var g = "Your item will be delivered between " + now.add("days".c).format("Do MMMM") + " and " + now.add("days",d).format("Do MMMM");

var h = document.getElementById('contacts');
h.innerHTML = g

var i = document.getElementById('groups');
i.innerHTML = f

$(function() {
    $types = $('.syncTypes');
    $contacts = $('#contacts');
    $groups = $('#groups');
    $types.change(function() {
        $this = $(this).val();
        if ($this == "types") {
            $groups.slideUp(300);
            $contacts.delay(200).slideDown(300);
        }
        else if ($this == "groups") {
            $contacts.slideUp(300);
            $groups.delay(200).slideDown(300);
        }
    });
});

11 个答案:

答案 0 :(得分:51)

你走了!

function addWeekdays(date, days) {
  date = moment(date); // use a clone
  while (days > 0) {
    date = date.add(1, 'days');
    // decrease "days" only if it's a weekday.
    if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
      days -= 1;
    }
  }
  return date;
}

你这样称呼它

var date = addWeekdays(moment(), 5);

我使用.isoWeekday代替.weekday,因为它不依赖于区域设置(.weekday(0)可以是星期一或星期日)。

不要减去工作日,即addWeekdays(moment(), -3)否则这个简单的函数将永远循环!

更新了JSFiddle http://jsfiddle.net/Xt2e6/39/(使用不同的momentjs cdn)

答案 1 :(得分:22)

那些迭代循环解决方案不符合我的需求。 它们对于大数字来说太慢了。 所以我制作了自己的版本:

https://github.com/leonardosantos/momentjs-business

希望你觉得它很有用。

答案 2 :(得分:10)

forp的{p> 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 :(得分:4)

如果你想要一个高性能的@ acorio代码样本(使用@ Isantos&#39; s优化)并且可以处理负数,请使用:

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');
    if(date.isoWeekday() !== 6 && date.isoWeekday() !== 7)
      remaining -= increment;
  }
  return date;
};

请参阅此处的小提琴:http://jsfiddle.net/dain/5xrr79h0/

答案 4 :(得分:4)

我知道这个问题很久以前就已发布了,但如果有人碰到这个问题,这里是使用moment.js的优化解决方案:

function getBusinessDays(startDate, endDate){
  var startDateMoment = moment(startDate);
  var endDateMoment = moment(endDate)
  var days = Math.round(startDateMoment.diff(endDateMoment, 'days') - startDateMoment .diff(endDateMoment, 'days') / 7 * 2);
  if (endDateMoment.day() === 6) {
    days--;
  }
  if (startDateMoment.day() === 7) {
    days--;
  }
  return days;
}

答案 5 :(得分:3)

我建议在原型时添加一个函数。

这样的事可能吗? (另)

    nextWeekday : function () {
        var day = this.clone(this);
        day = day.add('days', 1);
        while(day.weekday() == 0 || day.weekday() == 6){
          day = day.add("days", 1);              
        }
        return day;
    },
    nthWeekday : function (n) {
        var day = this.clone(this);
        for (var i=0;i<n;i++) {
          day = day.nextWeekday();
        }
        return day;
    },

当你完成并编写了一些测试时,请发送拉取请求以获得奖励积分。

答案 6 :(得分:1)

如果你想要一个纯JavaScript版本(不依赖于Moment.js),试试这个......

function addWeekdays(date, days) {
    date.setDate(date.getDate());
    var counter = 0;
        if(days > 0 ){
            while (counter < days) {
                date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow
                var check = date.getDay(); // turns the date into a number (0 to 6)
                    if (check == 0 || check == 6) {
                        // Do nothing it's the weekend (0=Sun & 6=Sat)
                    }
                    else{
                        counter++;  // It's a weekday so increase the counter
                    }
            }
        }
    return date;
}

你这样称呼它......

var date = addWeekdays(new Date(), 3);

此功能每隔一天检查一次,看它是在星期六(第6天)还是星期日(第0天)。如果为真,则计数器不会增加,但日期会增加。 此脚本适用于小日期增量,例如一个月或更短时间。

答案 7 :(得分:0)

const calcBusinessDays = (d1, d2) => {
    // Calc all days used including last day ( the +1 )
    const days = d2.diff(d1, 'days') + 1;

    console.log('Days:', days);

    // how many full weekends occured in this time span
    const weekends = Math.floor( days / 7 );

    console.log('Full Weekends:', weekends);

    // Subtract all the weekend days
    let businessDays = days - ( weekends * 2);

    // Special case for weeks less than 7
    if( weekends === 0 ){
    const cur = d1.clone();
    for( let i =0; i < days; i++ ){
        if( cur.day() === 0 || cur.day() === 6 ){
        businessDays--;
        }
        cur.add(1, 'days')
    }
    } else {
    // If the last day is a saturday we need to account for it
    if (d2.day() === 6 ) {
        console.log('Extra weekend day (Saturday)');
        businessDays--;
    }
    // If the first day is a sunday we need to account for it
    if (d1.day() === 0) {
        console.log('Extra weekend day (Sunday)');
        businessDays--;
    }
    }

    console.log('Business days:', businessDays);
    return businessDays;
}

答案 8 :(得分:0)

d1和d2是作为参数传递给calculateBusinessDays

的时刻
calculateBusinessDays(d1, d2) {
    const days = d2.diff(d1, "days") + 1;
    let newDay: any = d1.toDate(),
    workingDays: number = 0,
    sundays: number = 0,
    saturdays: number = 0;
    for (let i = 0; i < days; i++) {
        const day = newDay.getDay();
        newDay = d1.add(1, "days").toDate();
        const isWeekend = ((day % 6) === 0);
        if (!isWeekend) {
            workingDays++;
        } 
        else {
            if (day === 6) saturdays++;
            if (day === 0) sundays++;
        }
    }
        console.log("Total Days:", days, "workingDays", workingDays, "saturdays", saturdays, "sundays", sundays);
    return workingDays;
}

答案 9 :(得分:0)

这可以在两个日期之间不循环的情况下完成。

// get nb of weekend days
var startDateMonday = startDate.clone().startOf('isoWeek');
var endDateMonday = endDate.clone().startOf('isoWeek');

var nbWeekEndDays = 2 * endDateMonday.diff(startDateMonday, 'days') / 7;
var isoDayStart = startDate.isoWeekday();
if (isoDayStart > 5) // starts during the weekend
{
    nbWeekEndDays -= (8 - isoDayStart);
}
var isoDayEnd = endDate.isoWeekday();
if (isoDayEnd > 5) // ends during the weekend
{
    nbWeekEndDays += (8 - isoDayEnd);
}

// if we want to also exlcude holidays
var startOfStartDate = startDate.clone().startOf('day');
var nbHolidays = holidays.filter(h => {
    return h.isSameOrAfter(startOfStartDate) && h.isSameOrBefore(endDate);
}).length;

var duration = moment.duration(endDate.diff(startDate));
duration = duration.subtract({ days: nbWeekEndDays + nbHolidays });

var nbWorkingDays = Math.floor(duration.asDays()); // get only nb of complete days

答案 10 :(得分:0)

我从开始日期到结束日期进行迭代,并且只计算工作日的天数。

const calculateBusinessDays = (start_date, end_date) => {
        const d1 = start_date.clone();
        let num_days = 0;
        while(end_date.diff(d1.add(1, 'days')) > 0) {
                if ([0, 6].includes(d1.day())) {
                        // Don't count the days
                } else {
                        num_days++;
                }
        }
        return num_days;
}