In my application i have start datetime picker and end datetime picker. any idea how to calculate hours between two dates excluding weekend in AngularJS.
Asked
Active
Viewed 260 times
1
-
Are you using any library like `moment`?? – Abhisar Tripathi Jan 24 '20 at 09:04
-
Go over [this answer](https://stackoverflow.com/a/28313068/5247200), then it should be straightforward to convert days to hours. And, like @AbhisarTripathi advised, `moment.js` is very helpful when doing non-standard work with data/time in JS. – David Jan 24 '20 at 09:09
1 Answers
0
Here is a function that will count only business workday hours for you using moment.js
library -:
function calculateWorkDays(start, end) {
if (moment(end, "YYYY-MM-DD").isBefore(start, "YYYY-MM-DD")) {
return null;
}
var duration = moment.duration(
moment(end, "YYYY-MM-DD").diff(moment(start, "YYYY-MM-DD"))
);
var hours = duration.asHours();
var days = moment.duration(
moment(end, "YYYY-MM-DD").diff(moment(start, "YYYY-MM-DD"))
)._data.days;
for (let i = 0; i < days; i++) {
if (
[6, 7].includes(
moment(start, "YYYY-MM-DD")
.add(i, "days")
.day()
)
) {
hours -= 24;
}
}
console.log(hours);
return hours;
}

Abhisar Tripathi
- 1,569
- 10
- 21