gpt4 book ai didi

javascript - 在 JavaScript 中计算不包括周末和假期的天数

转载 作者:行者123 更新时间:2023-11-29 10:59:32 24 4
gpt4 key购买 nike

我正在尝试编写一个代码,计算总天数,不包括周末和自定义假期。我搜索了 stackoverflow 和 adobe 论坛以找到解决方案并提供了以下代码。如果公众假期正好在工作日(周六至周三),则不计入计算。我的问题是,如果公共(public)假期在周末(周四至周五),则两者(假期和周末)都会扣除。假设休假持续时间为 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;
}

最佳答案

您应该为此使用一个库,而不是重新发明轮子。

但是如果你想自己做,你可以使用 .getDay 来检查公共(public)假期是否在周末。

var weekend = [4, 5],   // for Thursday, Friday
holDate, holDay;
for (var i = 0; i < hdayar.length; i++){
holDate = Date.parse(hdayar[i]);
holDay = new Date(holDate).getDay()
if (weekend.indexOf(holDay) == -1 && holDate >= Date.parse(start) && holDate <= Date.parse(end)) {
phdays ++;
}
}

phdays 现在将包含范围内非周末公共(public)假期的数量。

关于javascript - 在 JavaScript 中计算不包括周末和假期的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49958318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com