【问题标题】:How to exclude holidays dates in Angular/Javascript如何在 Angular/Javascript 中排除假期日期
【发布时间】:2020-11-04 21:12:45
【问题描述】:

我无法找到解决此问题的方法。拜托,我写了这段代码来计算休假期间工作时间之间的差异,我还记下了午餐时间和周末。但是,我想延长它以适应假期。例如,如果数组 ['2020-07-15', '2020-07-16', 2020-07-17'] 中的日期是假期。请问,如何根据数组中传递的日期排除这些假期。谢谢

onChangeDate(){
var minutesWorked = 0;
var startDate = new Date(this.leaveList.date_from);
var endDate = new Date(this.leaveList.date_to);
var holidays = [ new Date (2020, 6, 27), new Date(2020, 6, 28 )]
if(endDate < startDate){
    return 0;
}
var current  = startDate
// Define work range
var workHoursStart = 8.30;
var workHoursEnd = 18;
var excludeWeekends = true;
var excludeLunch = true;
// Loop while currentDate is less than end Date (by minutes)
while(current <= endDate){   
       
    if(current.getHours() >= workHoursStart && current.getHours() < workHoursEnd && (excludeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)
    &&(excludeLunch ? current.getHours() !== 12 && current.getHours() !==13.30: true)){
        
          minutesWorked++;
    }
    current.setTime(current.getTime() + 1000 * 60);
}
this.leaveList.hours = Math.floor(minutesWorked / 60);
}

【问题讨论】:

    标签: javascript jquery angularjs angular


    【解决方案1】:

    您应该尝试另一种方法,该方法不仅不会节省迭代次数,而且会提供有效的解决方案。

    1. 找出每天的小时数(调节午餐时间)
    2. 查找天数(调整周末天数)

    function onChangeDate(){
      var minutesWorked = 0;
      var startDate = new Date(this.leaveList.date_from);
      var endDate = new Date(this.leaveList.date_to);
      var holidays = [ new Date (2020, 6, 27), new Date(2020, 6, 28 )];
      holidays = holidays.map(function(holidayDate){
        return holidayDate.toDateString();
      })
      if(endDate < startDate){
        return 0;
      }
      var current  = startDate
      // Define work range
      var workHoursStart = 8.5;
      var workHoursEnd = 18;
      var excludeWeekends = true;
      var excludeLunch = true;
      var lunchTime = 1.5; // define just the no of hours of lunch
      var hoursPerDay = workHoursEnd - workHoursStart;
      if(excludeLunch){
        hoursPerDay = hoursPerDay - lunchTime;
      }
      var noOfDays = 0;
      while(current <= endDate){
        var currentDateValue = current.toDateString();
        var currentDay = current.getDay();
        if((!excludeWeekends || (excludeWeekends && currentDay < 6 && currentDay > 0))
           && holidays.indexOf(currentDateValue) == -1){
          noOfDays++;
        }
        current.setDate(current.getDate() + 1);
      }
      
      var hours = hoursPerDay*noOfDays;
      this.leaveList.hours = hours;
    
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多