gpt4 book ai didi

javascript - 查找日期范围内的工作日

转载 作者:行者123 更新时间:2023-12-01 01:58:47 26 4
gpt4 key购买 nike

我正在尝试将日期推送到数组中的某个范围内,但它仅推送最后一个日期 n 次,而不是所需的单个日期。

function getBusinessDatesCount(startDatetest, endDatetest) {
var curDate = startDatetest;
var weekdays = [];
while (curDate <= endDatetest) {
var dayOfWeek = curDate.getDay();
if (!((dayOfWeek === 6) || (dayOfWeek === 0))) {
weekdays.push(curDate);
}
curDate.setDate(curDate.getDate() + 1);
}
console.log(weekdays);
}
var startDatetest = new Date('05/03/2016');
var endDatetest = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDatetest, endDatetest);

enter image description here

最佳答案

当前内存中只有两个 date 对象,startDatetestendDatetest - 更改 curDate 将更改 startDatetest,因为对象变量本质上引用 Javascript 中的内存位置。 (创建引用该对象的新变量,例如 curDate = startDatetest,不会克隆该对象,它只会复制对内存中对象位置的引用)。您需要克隆date对象:

function getBusinessDatesCount(startDatetest, endDatetest) {
var curDate = startDatetest;
var weekdays = [];
while (curDate <= endDatetest) {
var dayOfWeek = curDate.getDay();
if (!((dayOfWeek === 6) || (dayOfWeek === 0))) {
weekdays.push(new Date(curDate.getTime()));
}
curDate.setDate(curDate.getDate() + 1);
}
console.log(weekdays);
}
var startDatetest = new Date('05/03/2016');
var endDatetest = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDatetest, endDatetest);

关于javascript - 查找日期范围内的工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782044/

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