首页 > 解决方案 > 工作日计数器跳过周末后的第一个星期一

问题描述

我知道有人问过类似的问题,但我似乎无法在其中任何一个中找到答案。所以我需要只使用 JavaScript 制作一个工作日计数器。目的是计算两个日期之间的工作日。

除了开始日期在星期六或星期日时,我的大部分工作都在工作,下一个星期一不计算在内,并且输出短了一天。我知道发生这种情况是因为变量计数被初始化为 0,并且它不会随着迭代而增加,但我不知道该怎么做才能解决这个问题。但是,发生这种情况后,其他一切都可以正常工作。

我尝试了多种方法,但似乎不知道该怎么做。任何建议将不胜感激。我正在粘贴下面的代码供任何人查看。

let eta='2020-07-23';
let req='2020-07-31T10:33:21.000Z';
let results;

//uncomment to check if the output is correct
window.alert(weekdayCount(eta,req));

function weekdayCount(d1,d2)
{   
    var tempEndDate = new Date(d2);
    tempEndDate.setHours(0,0,0,1);          //set the end dates time to midnight.
    var startDate = Date.parse(d1);
    var endDate = Date.parse(tempEndDate);

    //ensure that d1 is always 'smaller' than d2
    if(startDate<endDate)
    {
        //count is the number of working days
        var count = 0;
        var curDate = new Date(d1);
        var tempDay = curDate.getDay();
        var newStartDate = Date.parse(curDate);
        
        //uncomment to view outputs
        //window.alert(curDate);
        //window.alert(tempDay);
        //window.alert(newStartDate);
        //window.alert(endDate);

        //run the loop while start date is less than or equal to end date
        while (newStartDate <= endDate)
        {
            //when dayofWeek is not 6 or 0 i.e. Saturday and Sunday, increment count 
            if(!((tempDay === 6) || (tempDay === 0)))
            {
                count++;
            }
            
            //update the date by adding a new day to input date each iteration
            curDate.setDate(curDate.getDate() + 1);
            tempDay = curDate.getDay();
            newStartDate = Date.parse(curDate);
            
            //uncomment to view outputs.
            //window.alert(curDate);
            //window.alert(tempDay);
            //window.alert(newStartDate);
            //window.alert(endDate);
            //window.alert(count);
        }
        
        results = count;
    }
    else
    {
        //alert if d1 is greater than d2
        results = window.alert("ETA must be smaller than REQ.");
    }
    
    //return no. of working days
    return results;
}

标签: javascriptcounterweekday

解决方案


推荐阅读