【发布时间】:2021-01-07 15:14:59
【问题描述】:
我正在制作员工管理主页。 我想获得两个日期之间的营业时间。 我已经从这个链接搜索并获得了一种方法。 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;
}
请任何人帮助。谢谢。
【问题讨论】:
标签: javascript date