0

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.

2 Answers 2

0

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

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));

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.