简体   繁体   中英

subtract days and hours from business hours in javascript

can someone show me how to subtract days/hours from business days/hours?

Suppose a user enters a date and time in the future and based on the time space between this date and the current date, the code will subtract a number of days and hours, keeping into account holidays and weekends.

It is very difficult to do that because there is no variable that specifies which day is a vacation. That's why I wrote a code here that doesn't count the weekends and the specified vacations. But the problem is that you would have to specify all vacations in the „holiday“-variable.

 //specify here the holidays //For example the 14.11. and the 15.11. will count as holidays var holidays = ["14.11.", "15.11."]; function get_distance(date1, date2) { var distance = date1.getTime() - date2.getTime(); var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); return [days, hours]; } function output(text) { document.getElementById("output").innerText = text; } function myFunction(elm) { var value = elm.value; const d1 = new Date(value); const d2 = new Date(); var distance = get_distance(d1, d2); var i; var count = 0; for (i = 0; i < distance[0]; i++) { var d3 = d2; d3.setDate(d3.getDate()+1); var week = d3.toString().substr(0, 3).toLowerCase(); if (week != "sat" && week != "sun") { var month = d3.getMonth()+1; var day = d3.getDate(); var allow = true; for (var i2 of holidays) { if (i2 == `${day}.${month}.`) { allow = false; break; } } if (allow) { count++; } } } var hours = distance[1]; if (hours < 0) { hours = 0; } output(`Distance between now and the selected date without holidays and weekends: ${count}d ${hours}h`); }
 <input onchange="myFunction(this)" type="date"> <p id="output"></p>

I hope this code helps you a bit!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM