How do you get the first working day of the month in javascript?

How can I write a function that returns the date object of the following month's first workday [monday through friday] without using Moment.js? this code gets me the last businesss day of the month but i'd like to switch it to get me the first day of next month.

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;

}

asked Dec 17, 2018 at 21:04

3

You can generate a date for the first of the month, and if it's a Sunday add one day, if it's a Saturday add two days.

You should also consider the name carefully. Not every Monday to Friday is a business day as some are holidays, and in many cultures and occupations the business week is not Monday to Friday.

/*  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

Chủ Đề