Home > Software design >  Get WorkDates by Monthdate javascript
Get WorkDates by Monthdate javascript

Time:09-27

I wonder if it is possible to get the workdays(mon-fri) by month and year. The input is a month year the output a list of dates. For example: I give Month 1 and year 2020. I want to get: mon 01-01, tue 02-01, wed 03-01, thu 04-01, fri 05-01, mon 08-01 etc.

CodePudding user response:

You could simply try creating an array which will first contain the date objects for the first day of each months. It should be like this: const MyDates= ["1ST DATE OBJECT", "2ND DATE OBJECT", ..., "upto Dec"];

You can then try to loop through each date object and use the getDay() method to get the weekday of that particular date.

CodePudding user response:

Yes it's possible. Get the first day of your month. Then iterate over all days to find the week days.

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)
getWeekDates(2022, 8);

  • Related