如何在 Angular/Javascript 中排除假期日期

Posted

技术标签:

【中文标题】如何在 Angular/Javascript 中排除假期日期【英文标题】:How to exclude holidays dates in 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);

【问题讨论】:

【参考方案1】:

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

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

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;

【讨论】:

以上是关于如何在 Angular/Javascript 中排除假期日期的主要内容,如果未能解决你的问题,请参考以下文章

最近的聊天应该在 quickblox 历史列表中排在第一位

如何从单元测试中排除名称中带有“Test”的帮助项目?

如何中断字符串,使它不在源代码中排成一行?

当解析 JSONArray 在 Retrofit 列表中排在最后时?

如何在 Angular/Javascript 中排除假期日期

如何调试 Angular JavaScript 代码