我有一个表单,用户从日历中获取两个日期。我想检查用户选择的两个日期之间的天数是从星期五到星期一(包括)。
我找到了平日计算的脚本(包括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
}
如何修改它以包括星期五和星期一?
答案 0 :(得分: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。 如果您想要其他日子,唯一需要更改的行是if语句嵌套在for循环中。