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

标签 javascript php jquery

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

相关文章:

php - 存在未知列的 MySQL 警告

jquery - 如何在页面加载时自动滚动窗口到某个高度

javascript - 阴影框叠加单击淡出

javascript - 阻止 Umbraco/TinyMce 将绝对 URL 转换为相对 URL

php - mysqli->prepare 函数返回 null

javascript - 在 JavaScript 中复制任意 n 维数组?

php - 多个 document.write 不工作

javascript - 当我将鼠标快速移出绘图时,jQuery flot 工具提示不会隐藏

javascript - jQuery .hover 无法工作

javascript - 如何在同一页面打开内容显示的各个链接