javascript - 使用 JavaScript 计算工作日并考虑假期

标签 javascript date

我如何调整该问题中的代码以考虑国家法定节假日。

Getting Working Days Using Javascript

我知道我需要一组假期日期,但是需要在逻辑中添加什么?

最佳答案

获取一系列假期实际上可能不是故事中最简单的部分。

无论如何,我假设您最终会得到一个 [ 年、月、日 ] 格式的日期数组。还有另一种可能性是存储完整的 Date 对象,这可能更适合也可能不适合,具体取决于您的导入方法。

下面是一个非常简化且明显不完整的:

const holidays = [
  [ 2015,  1,  1 ], [ 2015,  1, 19 ], [ 2015,  7,  4 ], [ 2015, 12, 25 ],
  [ 2016,  1,  1 ], [ 2016,  1, 18 ], [ 2016,  7,  4 ], [ 2016, 12, 25 ],
  [ 2017,  1,  1 ], [ 2017,  1, 16 ], [ 2017,  7,  4 ], [ 2017, 12, 25 ]
];

这里有一些代码可以帮助您入门:

const holidays = [
  [ 2015,  1,  1 ], [ 2015,  1, 19 ], [ 2015,  7,  4 ], [ 2015, 12, 25 ],
  [ 2016,  1,  1 ], [ 2016,  1, 18 ], [ 2016,  7,  4 ], [ 2016, 12, 25 ],
  [ 2017,  1,  1 ], [ 2017,  1, 16 ], [ 2017,  7,  4 ], [ 2017, 12, 25 ]
];

function isHoliday(ts) {
  var year  = ts.getFullYear(),
      month = ts.getMonth(),
      day   = ts.getDate();

  return holidays.some(function(d) {
    return d[0] == year && d[1] == month + 1 && d[2] == day;
  });
}

function getWorkingDays(ts, end) {
  for(var cnt = 0; ts.getTime() <= end.getTime(); ts.setDate(ts.getDate() + 1)) {
    // increment counter if this day is neither a Sunday,
    // nor a Saturday, nor a holiday
    if(ts.getDay() != 0 && ts.getDay() != 6 && !isHoliday(ts)) {
      cnt++;
    }
  }
  return cnt;
}

console.log(getWorkingDays(new Date('2015-12-20'), new Date('2016-01-03')));
console.log(getWorkingDays(new Date('2016-12-20'), new Date('2017-01-03')));

关于javascript - 使用 JavaScript 计算工作日并考虑假期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589517/

相关文章:

javascript - 如何设置选择选项来更改表单操作

vba - 并非所有日期都能被 VBA 识别

返回 x 天前日期的 Python 函数

javascript - 自动将动态添加的对象属性(函数)包装在包装函数中

javascript - 选项 onclick 替代方案

javascript - 计算 Google Apps 脚本中两个日期之间的差异

javascript - 我在使用拖放 API 获取元素的 ID 时遇到问题

python - 用于检查到期日期的代码,来自一个 python 脚本输出

r - 仅用工作日填充向量

javascript - 我没有在 javascript 0000-00-00 00 :00:00 中获得准确的 mysql 默认时间格式