gpt4 book ai didi

javascript - 周末、节假日计算在两个日期之间,无需迭代

转载 作者:行者123 更新时间:2023-11-30 12:49:36 28 4
gpt4 key购买 nike

我必须计算以下两个日期之间的周末计数和假期计数。

var startDate = new Date("01/02/2014");
var endDate = new Date("02/06/2014");
var holidays = [new Date("01/06/2014"), new Date("01/26/2014")];

最佳答案

这循环了部分周,因此最多有 6 次迭代。我想不出更优雅的方法来用纯 JS 解决这个问题。

var startDate = new Date("01/02/2014");
var endDate = new Date("02/06/2014");

var diff = Math.abs(startDate - endDate); // in milliseconds
var ms_per_day = 1000*60*60*24;
var days = diff/ms_per_day + 1; // convert to days and add 1 for inclusive date range
var mod = days % 7;
var full_weeks = (days - mod) / 7;

var weekend_days = full_weeks * 2;

if (mod != 0) { // iterate through remainder days
var startPartialWeek = new Date();
var endPartialWeek = endDate;
startPartialWeek.setTime(endDate.getTime() - (mod - 1)*ms_per_day);
for (var d = startPartialWeek; d <= endPartialWeek; d.setDate(d.getDate() + 1)) {
if(d.getDay() == 0 || d.getDay() == 6) {
weekend_days++;
}
}
}

alert(weekend_days);

这只计算周六和周日,不包括节假日。我认为如果不遍历从其他来源获得的假期日期集合,您将无法安排假期。

关于javascript - 周末、节假日计算在两个日期之间,无需迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21413906/

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