请假时间算法

3,069 阅读1分钟
功能说明:
1、开始时间小于9点从9点开始
2、结束时间大于18点 算到18点
3、开始时间-结束时间 跨越 12-13 点 请假小时数减去一个小时
4、按一天8小时这算成请假天数
5、不满一个小时按一个小时算
代码
const formatTime = function(time){
  let y = time.getFullYear()
  let m = time.getMonth() + 1
  let d = time.getDate()
  let h = time.getHours()
  let mm = time.getMinutes()
  return {
    year: y,
    month: m,
    day: d,
    hours: h,
    minutes: mm
  }
}
const diffTime = function(begin_time, endtime){ // 返回间隔时间
    if (!begin_time || !endtime) {
        return '';
    }
    const oneHours = 60 * 60 * 1000;
    // 返回间隔时间
    begin_time = new Date(begin_time);
    endtime = new Date(endtime);
    let s_time = formatTime(begin_time);
    let e_time = formatTime(endtime);
    let diff_day =
        (+new Date(`${e_time.year}/${e_time.month}/${e_time.day}`) -
            +new Date(`${s_time.year}/${s_time.month}/${s_time.day}`)) /
        (24 * oneHours);
    let diff_hours; // 间隔小时

    if (s_time.hours < 9) {
        // 开始小时早于9点,从9点起算
        s_time.hours = 9;
        s_time.minutes = 0;
    }

    if (s_time.hours >= 12 && s_time.hours < 13) {
        // 开始时间在中午,从13点算
        s_time.hours = 13;
        s_time.minutes = 0;
    }
    if (e_time.hours >= 12 && e_time.hours < 13) {
        // 结束时间在中午,从13点算
        e_time.hours = 13;
        e_time.minutes = 0;
    }
    if (e_time.hours >= 18) {
        // 结束时间晚于18点,到18点止
        e_time.hours = 18;
        e_time.minutes = 0;
    }

    if (diff_day < 1) {
        // 不跨天
        diff_hours =
            (+new Date(
                `2019/01/01 ${e_time.hours}:${e_time.minutes}:00`
            ) -
                new Date(
                    `2019/01/01 ${s_time.hours}:${s_time.minutes}:00`
                )) /
            oneHours;
        diff_hours =
            s_time.hours < 12 && e_time.hours >= 13
                ? diff_hours - 1
                : diff_hours;
        if (s_time.hours >= 18 || e_time.hours < 9) {
            diff_hours = 0;
        }
    } else {
        // 跨天
        // 开始天请假时间:小时
        let s_diff_time =
            (+new Date(`2019/01/01 18:00:00`) -
                new Date(
                    `2019/01/01 ${s_time.hours}:${s_time.minutes}:00`
                )) /
            oneHours;
        // 结束天请假时间
        let e_diff_time =
            (+new Date(
                `2019/01/01 ${e_time.hours}:${e_time.minutes}:00`
            ) -
                new Date(`2019/01/01 09:00:00`)) /
            oneHours;

        s_diff_time = s_time.hours >= 18 ? 0 : s_diff_time;
        e_diff_time = e_time.hours < 9 ? 0 : e_diff_time;
        diff_hours = s_diff_time + e_diff_time;
        diff_hours = s_time.hours < 12 ? diff_hours - 1 : diff_hours;
        diff_hours = e_time.hours >= 13 ? diff_hours - 1 : diff_hours;
        diff_hours = (diff_day - 1) * 8 + diff_hours;
    }
    return +(Math.ceil(diff_hours) / 8).toFixed(3);
}