繁体   English   中英

如何检查两个日期之间的天数是否为工作日?

[英]How to check if days between two dates are weekdays?

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

我找到了平日计算的脚本(包括satuday和星期日的天数):

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
}

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

把这个放在一起很快,但它应该工作。 我无法理解您的示例代码。 只是觉得这可能会好一点。

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。 如果你想要其他日子,唯一需要更改的行是if语句嵌套在for循环中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM