我已经得到了两个日期之间的差异。现在我需要排除周末并将其显示在持续时间输入中。例如:我选择日期从(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/