javascriptdatedaysmonthcalendaroutsystems

Get WorkDates by Monthdate javascript


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.


Solution

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