2013-05-21 130 views
0

我有一个窗体,用户从日历中取两个日期。我想检查用户选择的两个日期之间的日期是从星期五到星期一(包括)。如何检查两个日期之间的日期是星期几?

我发现脚本,算工作日(天是包括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 
} 

如何修改它包括周五和本周一?

+2

你在问如何获得两个日期之间的天数而不是工作日? – epascarello

+0

我知道这可能是一个语言障碍问题,但您能否更具体些?我真的不明白你想要的“预期”结果是什么? – SpYk3HH

回答

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语句。

相关问题