首页 > 解决方案 > javascript:获取下个月的第一个工作日

问题描述

如何在不使用 Moment.js 的情况下编写返回下个月第一个工作日(周一至周五)的日期对象的函数?这段代码让我得到了本月的最后一个工作日,但我想把它换成下个月的第一天。

function lastBusinessDayOfMonth(year, month) {
var date = new Date();
var offset = 0;
var result = null;

if ('undefined' === typeof year || null === year) {
    year = date.getFullYear();
}

if ('undefined' === typeof month || null === month) {
    month = date.getMonth();
}

do {
    result = new Date(year, month, offset);

    offset--;
} while (0 === result.getDay() || 6 === result.getDay());

return result;

}

标签: javascriptdate

解决方案


您可以为每月的第一天生成一个日期,如果是星期天,则添加一天,如果是星期六,则添加两天。

您还应该仔细考虑名称。不是每个星期一到星期五都是工作日,因为有些是假期,而且在许多文化和职业中,工作日不是星期一到星期五。

/*  Return first day in the following month that is Monday to Friday,
 *  or not Saturday or Sunday.
 * 
 *  @param {number|string} year - defaults to current year
 *  @param {number|string} month - defaults to current month
 *  @returns {Date} - first day of following month that is Monday to Friday
 */
function firstMonToFriNextMonth(year, month) {
  var d = new Date();
  d = new Date(Number(year)  || d.getFullYear(),
               Number(month) || d.getMonth() + 1,
               1);
  d.getDay() % 6? d : d.setDate((2 + d.getDay()) % 5);
  return d;
}

// No args
console.log(firstMonToFriNextMonth().toString());
// Year only
console.log(firstMonToFriNextMonth(2018).toString());
// Month only
console.log(firstMonToFriNextMonth(null, 1).toString());
// All of 2018
for (var i=1; i<13; i++) {
  console.log(firstMonToFriNextMonth(2018,i).toString());
}


推荐阅读