Js计算日期之间的工作日(去掉周六周日)
2017-12-25 本文已影响0人
luojunbang
//计算日期区间工作日
function countWorkDay(sDay, eDay) {
var s = new Date(sDay),
e = new Date(eDay);
var _sw = s.getDay(),
_ew = e.getDay();
console.log(s + " " + e);
if (s.getTime() <= e.getTime()) {
if (s.getTime() == e.getTime() && _sw > 0 && _sw < 6) {
console.log("同一天");
return 1;
} else if (s.getTime() == e.getTime() && (_sw == 0 || _sw == 6)) {
console.log("同一天周末");
return 0
} else {
var diffDay = (e - s) / (1000 * 60 * 60 * 24) + 1;
var firWeekday = _sw < 6 && _sw > 0 ? 6 - _sw : 0; //第一周的工作日
// console.log(firWeekday);
var lastWeekday = (_ew > 0 ? _ew : 0) - (_ew == 6 ? 1 : 0); //最后一周的工作日
var diffWeek = (diffDay - firWeekday - lastWeekday) > 0 ? Math.floor((diffDay - firWeekday - lastWeekday) / 7) : 0; //中间的周数
// console.log("diff: " + diffWeek);
if (diffWeek < 1) {
// 周数小于1
var __ew = _ew > 5 ? 5 : _ew;
var __sw = _sw == 0 ? 1 : _sw;
if (__ew >= __sw && diffDay < 7) {
// 同一周
return __ew - __sw + 1;
} else {
// 跨周
return firWeekday + lastWeekday;
}
} else {
return diffWeek * 5 + firWeekday + lastWeekday;
}
}
} else {
return -1; //日期区间错误
}
}
// 测试函数
function testFun() {
var _testSD = 1;
for (var i = 1; i < 8; i++) {
console.log("第" + i + "次测试");
for (var j = 1; j < 8; j++) {
console.log(countWorkDay("2017/12/" + i, "2017/12/" + j));
}
}
}