javascript - 工作日计数器跳过周末后的第一个星期一
问题描述
我知道有人问过类似的问题,但我似乎无法在其中任何一个中找到答案。所以我需要只使用 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;
}
解决方案
推荐阅读
- c++ - 性能优化嵌套循环
- javascript - webpack 4 - HMR 不刷新 html 和 scss (ReactJS)
- typescript - 在 .then() 中分配 Typescript 参数
- c# - Path. 组合两个相对路径字符串以创建新的相对路径
- sql-server - 如何填充仅包含标识列的表?
- javascript - 识别移动设备的纵向或横向模式和缩放级别(但不特定于浏览器)
- c# - 在对 odata 相关实体过滤请求的高效 EF 生成查询中,不使用 And 子句应用 Inner Join
- javascript - 如何在 nuxtServerInit() 中获取 cookie?
- module - 导入带有打开的头文件:命名空间/模块错误
- mysql - 通过单个查询从多个表中返回数据