0

我有表格,用户从日历中获取两个日期。我想检查用户选择的两个日期之间的天数是否从星期五到星期一(包括)。

我找到了计算工作日的脚本(包括星期六和星期日的日子):

function calcBusinessDays (dDate1, dDate2) {
    var iWeeks, iDateDiff, iAdjust = 0;

    if (dDate2 < dDate1) return 0;

    var iWeekday1 = dDate1.getDay();
    var iWeekday2 = dDate2.getDay();

    iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
    iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;

    if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend

    iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
    iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;

    // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
    iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)

    if (iWeekday1 <= iWeekday2) {
        iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
    } else {
        iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
    }

    iDateDiff -= iAdjust // take into account both days on weekend

    return (iDateDiff + 1); // add 1 because dates are inclusive
}

如何修改它以包括星期五和星期一?

4

1 回答 1

2

只需快速将其组合在一起,但它应该可以工作。我无法理解您的示例代码。只是认为这可能会更好一些。

var calcBusinessDays = function (dDate1, dDate2) {
    //We are working with time stamps
    var from = dDate1.getTime()
    ,   to = dDate2.getTime()
    ,   tempDate = new Date()
    ,   count = 0;

    //loop through each day between the dates 86400000 = 1 day
    for(var _from = from; _from < to; _from += 86400000){
        //set the day
        tempDate.setTime(_from);
        //If it is a weekend add 1 to count
        if ((tempDate.getDay() <= 1) || (tempDate.getDay() >= 5)) {
            count++;
        }
    }

    //return count =)
    return count;
}

这将为周五、周六、周日和周一加 1。如果您想要其他日子,唯一需要更改的行是嵌套在 for 循环中的 if 语句。

于 2013-05-21T15:19:49.207 回答