我正在制作员工管理主页。我想在两次约会之间安排营业时间。我已经搜索并从这个链接中获得了一个方法。http://rion.io/2014/06/20/calculating-business-hours-in-javascript/
// Simple function that accepts two parameters and calculates
// the number of hours worked within that range
function workingHoursBetweenDates(startDate, endDate) {
// Store minutes worked
var minutesWorked = 0;
// Validate input
if (endDate < startDate) { return 0; }
// Loop from your Start to End dates (by hour)
var current = startDate;
// Define work range
var workHoursStart = 9;
var workHoursEnd = 18;
var includeWeekends = false;
// Loop while currentDate is less than end Date (by minutes)
while(current <= endDate){
// Is the current time within a work day (and if it
// occurs on a weekend or not)
if(current.getHours() >= workHoursStart && current.getHours() < workHoursEnd && (includeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)){
minutesWorked++;
}
// Increment current time
current.setTime(current.getTime() + 1000 * 60);
}
// Return the number of hours
return minutesWorked / 60;
}
我尝试过这种方法,但当日期差异很大(如2020-01-01 12:45:00 - 2028-10-06 23:10:33
(时,性能会很差。
所以我自己做了新的功能。但有时是错误的。
function workingHoursBetweenDates(startDate, endDate) {
const startWeekday = startDate.getDay();
const endWeekday = endDate.getDay();
let workHours = Math.abs(endDate.getTime() - startDate.getTime()) / 3600000 / 3;
let restDays = Math.floor(workHours / 8 / 7) * 2;
workHours -= (restDays * 8);
return workHours;
}
请任何人帮忙。谢谢
我会优化你的问题,这样我就可以处理完整的日期了。
如果你取2020-01-01 12:45:00 - 2028-10-06 23:10:33
的范围,那么基本上有三个部分:
2020-01-01 12:45:00 - 2020-01-01 23:59:59
2020-01-02 00:00:00 - 2028-10-05 23:59:59
2020-10-06 00:00:00 - 2028-10-06 23:10:33
计算全天营业时间很简单:dayAmount * (dayEnd - dayStart) * 60
使用你能算出的任何方法来计算第1部分和第3部分的分钟数。然后把所有的东西加在一起。
编辑:另一方面,你甚至可能不得不把它分成每周的大块,因为它可能不是一整周。你必须计算假期的数量,除非你对天真的方法很满意。