gpt4 book ai didi

javascript - 使用.change javascript计算排除周末的2个日期

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

我已经得到了两个日期之间的差异。现在我需要排除周末并将其显示在持续时间输入中。例如:我选择日期从(2020年3月2日)到(2020年3月9日)持续时间应该显示6天,因为它需要扣除2天,即星期六和星期日。2/

$(document).ready(function(){
$('#FromDate').change(function(){

ToDate.min=document.getElementById('FromDate').value;
var start = new Date (document.getElementById('FromDate').value);
var end = new Date (document.getElementById('ToDate').value);
var duration = new Date();

var different = end.getTime() - start.getTime();
duration = (different/(1000*60*60*24))+1;
document.getElementById('duration').value = duration;
});


$('#ToDate').change(function(){
var start = new Date (document.getElementById('FromDate').value);
var end = new Date (document.getElementById('ToDate').value);
var duration = new Date();

var different = end.getTime() - start.getTime();
duration = (different/(1000*60*60*24))+1;
document.getElementById('duration').value = duration;
});

});

最佳答案

这是一个迭代日期以找出包含多少个周末的解决方案:

// this value is fetched again in order to keep the original value of 'start' from changing
let dateInRange = new Date (document.getElementById('FromDate').value);
let numberOfWeekendDaysInRange = 0;
// here we are making use of the existing 'end' object
while (dateInRange.toISOString() < end.toISOString()) {
if (isWeekend(dateInRange)) {
numberOfWeekendDaysInRange += 1;
}
// add a day; this internally takes care of shifting months and years
dateInRange = new Date(dateInRange.getFullYear(), dateInRange.getMonth(), dateInRange.getDate() + 1);
}

function isWeekend(date) {
// 0 is sunday, 6 is saturday
return date.getDay() === 0 || date.getDay() === 6;
}

剩下的就是从公式中减去 numberOfWeekendDaysInRange 值。

咨询Date docs使用的方法。

关于javascript - 使用.change javascript计算排除周末的2个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60611234/

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