2013-05-21 131 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語句。

相關問題