I'm making home page for employee management. I want to get business hours between two dates. I already searched and get one method from this link. 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;
}
I tried this method but performance is bad when date difference large such as 2020-01-01 12:45:00 - 2028-10-06 23:10:33
.
So I make new function myself. But sometimes is wrong.
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;
}
Please anyone help. thanks.