给公司做了一套系统,涉及到请假单功能开发。在计算请假时长这块总结一下:按天计算的就不总结了比较简单,这里总结一下按小时数计算的 ,话不多说,直接上代码
// 获取两个日期相差的工作小时(不包括节假日)
function getHour(StartTime, EndTime) {
StartTime = new Date(StartTime.replace(/-/g, '/'));
EndTime = new Date(EndTime.replace(/-/g, '/'));
var ms = Math.abs(EndTime.getTime() - StartTime.getTime());
// 实际工时(天) = 起止日期差 - 周六日数目。
if ((StartTime.getMonth() == EndTime.getMonth())
&& (StartTime.getDate() == EndTime.getDate())) {
// 若为同一日期
var hour1 = (getDayHour(StartTime.getHours(), StartTime.getMinutes(),
EndTime.getHours(), EndTime.getMinutes(), "1")).toFixed(1);
$("#xxtj").val(hour1.substring(0,hour1.length-2));// 按天计算
return hour1;
} else {
var sh=StartTime.getHours();
var eh= EndTime.getHours();
if (13 <= sh) {
if (8 <= eh && eh <= 12) {
var days = Math.ceil(ms / 1000 / 60 / 60 / 24) + 1;
}else{
var days = Math.floor(ms / 1000 / 60 / 60 / 24) + 1;
}
} else {
var days = Math.floor(ms / 1000 / 60 / 60 / 24) + 1;
}
var workDayVal = 0;
// 工时的余数
var remainder = days % 7;
// 工时向下取整的除数
var divisor = Math.floor(days / 7);
var weekendDay = 2 * divisor;
// 起始日期的星期,星期取值有(1,2,3,4,5,6,0)
var nextDay = StartTime.getDay();
// 从起始日期的星期开始 遍历remainder天
for (var tempDay = remainder; tempDay >= 1; tempDay--) {
// 第一天不用加1
if (tempDay == remainder) {
nextDay = nextDay + 0;
} else if (tempDay != remainder) {
nextDay = nextDay + 1;
}
// 周日,变更为0
if (nextDay == 7) {
nextDay = 0;
}
// 周六日
if (nextDay == 0 || nextDay == 6) {
weekendDay = weekendDay + 1;
}
}
workDayVal = days - weekendDay - 2;
var hour0 = (workDayVal * 8 + getDayHour(StartTime.getHours(),
StartTime.getMinutes(), EndTime.getHours(), EndTime
.getMinutes(), "0")).toFixed(1);
$("#xxtj").val(hour0.substring(0,hour0.length-2));// 按天计算
return hour0;
}
}
function getDayHour(sh, sm, eh, em, type) {
sh = parseInt(sh);
eh = parseInt(eh);
if (type == "0") {
// 计算非当天
if (8 <= sh && sh <= 12) {
sh = 12 - sh + 4;
} else if (13 <= sh && sh <= 17) {
sh = 17 - sh;
}
if (8 <= eh && eh <= 12) {
eh = eh - 8;
} else if (13 <= eh && eh <= 17) {
eh = eh - 13 + 4;
}
return parseFloat(sh + eh);
} else {
// 计算当天
if (sh == eh) {
// 在同一小时
if (sm == em) {
return 0;
} else {
return Math.abs((sm - em) / 60);
}
} else {
// 不在同一小时
// 开始时间在上午时间段,并且结束时间在下午时间段
if ((8 <= sh && sh <= 12) && (13 <= eh && eh <= 17)) {
if (sm == 30) {
return parseFloat(12 - sh + eh - 13);
} else if (sm < 30) {
return parseFloat(12 - sh + eh - 13);
} else if (sm > 30 && sh != 12) {
return parseFloat(12 - sh - 1 + eh - 13);
}
}
// 开始时间与结束时间都在上午时间段
if ((8 <= sh && sh <= 12) && (8 <= eh && eh <= 12)) {
if (sm == em) {
return parseFloat(Math.abs(eh - sh));
} else {
return parseFloat(Math.abs(eh - sh - 1) + (60 - sm) / 60
+ em / 60);
}
} else if (13 <= sh && sh <= 17 && 13 <= eh && eh <= 17) {
if (sm == em) {
return parseFloat(Math.abs(eh - sh));
} else {
return parseFloat(Math.abs(eh - sh - 1) + (60 - sm) / 60
+ em / 60);
}
}
}
}
}
因为都是整点的请,分钟数就不算了 。如有不对的地方,欢迎指教 !