【问题标题】:How to count number of days after excluding weekends using js如何使用js计算排除周末后的天数
【发布时间】:2021-11-09 08:08:20
【问题描述】:

我有一个查询,我需要计算从今天到给定数字的工作日数,

今天是 2021 年 9 月 14 日,给定的数字是 10 我想要最后一个日期 2021 年 9 月 28 日,因为它是从今天起的第 10 个工作日。我试着在下面计算不同的日子

    var startDate = new Date();
    var endDate = new Date();
    if(res.defaultLeadTime !== 0){
        endDate.setDate(startDate.getDate() + 10);
    }

我是 2021 年 9 月 24 日。现在我正在计算两个日期之间的周末

countWeekendDays = ( d0, d1 ) => {
    var ndays = 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
    var nsaturdays = Math.floor( (d0.getDay()+ndays) / 7 );
    return 2*nsaturdays + (d0.getDay()==0) - (d1.getDay()==6);
}

在计数中添加这些天数会给我另一个日期,但我很困惑,如果在新的日期范围内还有周末,那么我可以用这些天做什么。

所以任何人都可以请指导我。

【问题讨论】:

标签: javascript jquery date


【解决方案1】:

试试这个:

var startDate = "14-SEPT-2021";
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "", noOfDaysToAdd = 10, count = 0;
while(count < noOfDaysToAdd){
    endDate = new Date(startDate.setDate(startDate.getDate() + 1));
    if(endDate.getDay() != 0 && endDate.getDay() != 6){
       count++;
    }
}
alert(endDate);//You can format this date as per your requirement

【讨论】:

    【解决方案2】:

    另一种解决方案

    startDate = new Date("09/17/2021");  
    endDate = new Date("10/28/2021");  
    
     
    // Calculate days_difference = (endDate milliseconds - startDate milliseconds) / (1000 * 60 * 60 * 24) to get results in days  
    var days_difference = (endDate.getTime() - startDate.getTime()) / 86400000; 
     
    // Calculate number of weekends during the whole duration
    var weekdends = Math.floor(days_difference/7) * 2 ;
    
    // Adjust weekends depend on start days 
    (days_difference%7)+startDate.getDay() == 6 ? weekdends+=2 : 
      (days_difference%7)+startDate.getDay() == 5 ? weekdends+=1 :
      weekdends;
    
    // Calculate Working Days 
    var workDays = days_difference - weekdends
    
    console.log("Working days",(workDays));

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2015-02-03
    • 2023-04-09
    相关资源
    最近更新 更多