function getDuration(starTime, endTime) {//计算时长
let num1 = 0,num2 = 0;
num1 = parseInt(starTime.split(":")[0]) +parseInt(starTime.split(":")[1]) / 60;
num2 = parseInt(endTime.split(":")[0]) + parseInt(endTime.split(":")[1]) / 60;
return num2-num1
};
function DateDiff(sDate1, sDate2){//计算2018-03-23 至 2018-04-01之间的时间差,开始天数不计算在内
var aDate, oDate1, oDate2, iDays
aDate = sDate1.split("-")
oDate1 = new Date(aDate[1] + \'-\' + aDate[2] + \'-\' + aDate[0])
aDate = sDate2.split("-")
oDate2 = new Date(aDate[1] + \'-\' + aDate[2] + \'-\' + aDate[0])
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24)
return iDays
}
function calculateTimeOff(st,et) {//计算不是整天部分的请假时长
let m={key:null, duration:null},n={key:null, duration:null},o=null;
workTime.forEach((v,k)=>{
if(v[0]<= st && v[1] >= st){//开始时间在上班时间段内
m.key = k
m.duration = getDuration(st,v[1])
}
if(workTime[k+1]){//有下一个上班时间段
if(v[0]<et && v[1]>=et){//在上班时段内
n.key = k
n.duration = v[1] == et ? getDuration(v[0],v[1]) : getDuration(v[0],et)
}else if(et>v[1] && et < workTime[k+1][0]){//不在上班时段内
n.key = k
n.duration = getDuration(v[0],v[1])
}
}else{//没有下一个上班时间段
if(v[0]<et && v[1]>=et){//在上班时段内
n.key = k
n.duration = v[1] == et ? getDuration(v[0],v[1]) : getDuration(v[0],et)
}else if(v[0]<et && et > v[1]){//不在上班时段内
n.key = k
n.duration = getDuration(v[0],v[1])
}
}
});
if(n.key - m.key > 1){
workTime.forEach((v,k)=>{
if(m.key<k<n.key){
o = o + getDuration(v[1],v[0]);
}
});
return (o + m.duration + n.duration)/workHours;
}else if(n.key == m.key){
if(et>workTime[m.key][1]){
return (getDuration(st,workTime[m.key][1])/workHours);
}else{
return (getDuration(st,et)/workHours);
}
}else{
return (m.duration + n.duration)/workHours;
}
}
let workTime=["09:00","18:00"];
let workHours = 8;
let startTime = "2018-3-27 09:00".split(" ")[1];
let endTime = "2018-3-29 18:00".split(" ")[1];
let dayNum = DateDiff("2018-3-27 09:00".split(" ")[0],"2018-3-27 09:00".split(" ")[0])
if(dayNum == 0){
val.days = calculateTimeOff(startTime,endTime)
}else{
if(val.dateType==2){//请假时长计算 自然日
val.days = dayNum + calculateTimeOff(startTime, workTime[workTime.length-1][1]) + calculateTimeOff(workTime[0][0],endTime)-1
}else{//请假时长只计算工作日
let noUseDay = 0// 请假时段内有几天是休息日
let unixDb = new Date(val.startDate.split(" ")[0]).getTime()// 开始时间
let unixDe = new Date(val.endDate.split(" ")[0]).getTime()// 结束时间
for (let k = unixDb; k <= unixDe;) {//循环遍历 判断时间段内有几个周末
if (val.workDay.indexOf(new Date(k).getDay()) == -1) {
noUseDay = ++noUseDay
}
k = k + 24 * 60 * 60 * 1000
}
val.days = dayNum - noUseDay + calculateTimeOff(startTime, workTime[workTime.length-1][1]) + calculateTimeOff(workTime[0][0],endTime)-1
}
}