繁体   English   中英

从javascript中的营业时间中减去天数和小时数

[英]subtract days and hours from business hours in javascript

有人可以告诉我如何从工作日/小时中减去天/小时吗?

假设用户输入未来的日期和时间,并根据该日期和当前日期之间的时间间隔,代码将减去天数和小时数,同时考虑假期和周末。

这样做非常困难,因为没有指定哪一天是假期的变量。 这就是为什么我在这里写了一个不计算周末和指定假期的代码。 但问题是您必须在“holiday”变量中指定所有假期。

 //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>

我希望这段代码对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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