skywind
skywind

Reputation: 964

How to check if days between two dates are weekdays?

I have form where user take two dates from calendar. I want to check if days between two dates that user selected are in from friday to monday (include).

I found script that count weekdays (days that are include satuday and sunday):

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
}

how to modify it to include friday and monday?

Upvotes: 0

Views: 470

Answers (1)

bottens
bottens

Reputation: 3892

Just put this together real quick but it should work. I had trouble understanding your sample code. Just thought this might work a little better.

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;
}

This will add 1 for Friday, Saturday, Sunday and Monday. The only line that would need to be changed if you wanted other days would be the if statement nested in the for loop.

Upvotes: 2

Related Questions