gpt4 book ai didi

javascript - 计算Javascript中两个日期之间的工作日(节假日除外)

转载 作者:行者123 更新时间:2023-12-03 22:54:54 25 4
gpt4 key购买 nike

我有一个 JavaScript 函数,它可以计算两个日期之间的工作日,它可以工作,但问题是它不考虑假期。如何修改此函数,例如通过在异常数组中添加假期?

在网上搜索了这个问题,但没有找到有关假期异常(exception)的信息。

例如假期数组:

var holidays = ['2016-05-03','2016-05-05'];

我有一个函数来计算这个:

function workingDaysBetweenDates(d0, d1) {
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate < startDate)
return 0;

// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);

// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);

// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();

// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;

// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1

// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1

return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

在jsfiddle中做了一个例子:

JSFiddle example

也许还有一些其他函数可以在 Jquery 中轻松使用?

最佳答案

尝试:

var startDate = new Date('05/03/2016');
var endDate = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDate,endDate);

function getBusinessDatesCount(startDate, endDate) {
let count = 0;
const curDate = new Date(startDate.getTime());
while (curDate <= endDate) {
const dayOfWeek = curDate.getDay();
if(dayOfWeek !== 0 && dayOfWeek !== 6) count++;
curDate.setDate(curDate.getDate() + 1);
}
alert(count);
return count;
}

关于javascript - 计算Javascript中两个日期之间的工作日(节假日除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37069186/

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