【发布时间】:2018-04-21 17:18:51
【问题描述】:
我正在尝试编写一个代码,其中将计算除周末和自定义假期之外的总天数。我通过 stackoverflow 和 adobe 论坛搜索以找到解决方案并附带以下代码。 如果公共假期在工作日(周六至周三),则不计算在内。 我的问题是,如果公共假期是在周末(周四至周五),它会同时扣除(假期和周末)。假设休假持续时间为 18/09/2018-22/09/2018,总计数 2 天代替 3。再次为 17/10/2018-21/10/2018,总计数 1 天代替3天。 任何帮助或解决问题的任何想法都会很棒! 问候
//Thursday and Friday will be excluded as weekend.
var start = this.getField("From").value;
// get the start date value
var end = this.getField("To").value;
var end = util.scand("dd/mm/yyyy H:MM:SS", end + " 0:00:00");
var start =util.scand("dd/mm/yyyy H:MM:SS", start + " 0:00:00");
event.value = dateDifference(start, end);
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
// Set time to midday to avoid daylight saving and browser quirks
s.setHours(12,0,0,0);
e.setHours(12,0,0,0);
// Get the difference in whole days
var totalDays = Math.round((e - s) / 8.64e7);
// Get the difference in whole weeks
var wholeWeeks = totalDays / 7 | 0;
// Estimate business days as number of whole weeks * 5
var days = wholeWeeks * 5;
// If not even number of weeks, calc remaining weekend days
if (totalDays % 7) {
s.setDate(s.getDate() + wholeWeeks * 7);
while (s < e) {
s.setDate(s.getDate() + 1);
// If day isn't a Thursday or Friday, add to business days
if (s.getDay() != 4 && s.getDay() != 5) {
++days;
}
}
}
var hdayar = ["2018/02/21","2018/03/17","2018/03/26","2018/04/14","2018/05/01","2018/08/15","2018/09/2 1","2018/10/18","2018/10/19","2018/12/16","2018/12/25"];
//test for public holidays
var phdays = 0;
for (var i = 0; i <hdayar.length; i++){
if ((Date.parse(hdayar[i]) >= Date.parse(start)) && (Date.parse(hdayar[i]) <= Date.parse(end))) {phdays ++;}}
return days-phdays + 1;
}
【问题讨论】:
-
周四到周五是周末?
-
是的,周四到周五是周末(习惯了)
-
@Luca——在中东很常见。
-
您的代码似乎基于here 的答案,您应该提及这一点。此外,您不应使用内置解析器,请参阅Why does Date.parse give incorrect results?。时间不需要设置两次,你一开始好像设置为 00:00:00 就够了。无需将其设置为 12:00:00。
标签: javascript date