0

ユーザーがカレンダーから 2 つの日付を取得するフォームがあります。ユーザーが選択した 2 つの日付の間の日が金曜日から月曜日まで (含む) であるかどうかを確認したい。

平日(土曜日と日曜日を含む日)をカウントするスクリプトを見つけました:

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 に答える