Created
April 21, 2022 14:12
-
-
Save myesn/57362d051f796afc3dac778539e40ca2 to your computer and use it in GitHub Desktop.
按照指定规则计算 开始日期时间-结束日期时间 之间的时间差
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getTimes(val) { | |
const [startDateRaw, endDateRaw] = val; | |
const startDate = new Date(startDateRaw); | |
const endDate = new Date(endDateRaw); | |
const diffOfMilliseconds = endDate - startDate; // 时间差,单位毫秒 | |
const hoursOfDay = 24; // 一天的小时数 | |
const millisencondsOfMinute = 60 * 1000; // 每分钟的毫秒数 | |
const millisencondsOfHour = 60 * millisencondsOfMinute; // 每小时的毫秒数 | |
const millisencondsOfDay = hoursOfDay * millisencondsOfHour; // 每天的毫秒数 | |
const startHour = startDate.getHours(); | |
const endHour = endDate.getHours(); | |
// 得到天数 | |
const diffOfDays = Math.floor(diffOfMilliseconds / millisencondsOfDay); | |
// 得到不足一天的小时数 | |
const remainderMillisecondsOfDay = | |
diffOfMilliseconds % millisencondsOfDay; // 得到不足一天的毫秒数 | |
const diffOfHours = Math.floor( | |
remainderMillisecondsOfDay / millisencondsOfHour | |
); | |
// 得到不足一小时的分钟数 | |
// 不到30分钟 就算0.0小时 | |
// 超过30分钟没到60分钟,就算0.5小时 | |
// 等于60分钟就算一个小时 | |
const policyOfMinute = (minutes) => { | |
if (!minutes || minutes < 30) { | |
return 0; | |
} | |
if (minutes >= 30 && minutes < 60) { | |
return 0.5; | |
} | |
// 肯定不会执行到这里,因为传进来的分钟数必定 < 60 ,即不足 1 小时的分钟数 | |
throw Error("minutes 参数暂不支持传递大于或等于一小时的分钟数"); | |
}; | |
const remainderMillisecondsOfHour = | |
remainderMillisecondsOfDay % millisencondsOfHour; // 得到不足一小时的毫秒数 | |
const diffOfMinutes = policyOfMinute( | |
Math.floor(remainderMillisecondsOfHour / millisencondsOfMinute) | |
); // 不足一小时的毫秒数 / 每分钟的毫秒数 = 分钟数 | |
// 计算最终的小时数 | |
let totalHours = diffOfDays * hoursOfDay + diffOfHours + diffOfMinutes; | |
if (totalHours <= 0) { | |
return 0; | |
} | |
// 如果包含中午午休时间,就减去这午休的一小时 | |
if (startHour <= 12 && endHour >= 13) { | |
totalHours -= 1; | |
} | |
return totalHours; | |
}, | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment