按月日期获取工作日期 javascript

问题描述 投票:0回答:2

我想知道是否可以按月和年获取工作日(周一至周五)。 输入是月+年,输出是日期列表。 例如:我给出 2020 年 1 月和年份。我想得到:周一 01-01、周二 02-01、周三 03-01、周四 04-01、周五 05-01、周一 08-01 等。

javascript date days monthcalendar outsystems
2个回答
0
投票

是的,这是可能的。获取您所在月份的第一天。然后迭代所有日期以找到工作日。

function getWeekDates(_year, _month) {
  let firstDay = new Date(_year, _month);
  const month = firstDay.getMonth();
  const weekDays = [];
  for (let i = 1; i < 32; i++) {
    const date = new Date(_year, month, i);
    // the ith day of the month is in the next month, so we stop looping
    if (date.getMonth() !== month) {
      break;
    }
    const day = date.getDay();
    // push to week days if it's not a Sunday or a Saturday
    if (day > 0 && day < 6) {
      weekDays.push(formatDate(date));
    }
  }
  return weekDays;
}

function formatDate(date) {
  // replace this by your favourite date formatter
  const days = ["Sun", "Mon", "Tues", "Wed", "Thrus", "Fri", "Sat"];
  return `${days[date.getDay()]} ${date.getDate()}-${date.getMonth() + 1}`;
}

// Get for September 2022 (Note months start with January being index 0)
console.log(getWeekDates(2022, 8));


0
投票

您可以简单地尝试创建一个数组,该数组首先包含每个月第一天的日期对象。 应该是这样的:

const MyDates= ["1ST DATE OBJECT", "2ND DATE OBJECT", ..., "upto Dec"];

然后,您可以尝试循环遍历每个日期对象并使用 getDay() 方法来获取该特定日期的工作日。

© www.soinside.com 2019 - 2024. All rights reserved.