Take only the days of the month by removing Saturday and Sunday with JAVASCRIPT / TYPESCRIPT

0

How can I add only the days of the month in an array by removing Saturday and Sunday?

user will inform the month and year and with this month I will get the days.

ex:

March 2018

1 2 5 6 7 8 9 12 13 14 15 16 19 20 21 22 23 26 27 28 29 30

    
asked by anonymous 09.03.2018 / 22:47

2 answers

2

Without the moment-js, why ... put an entire lib just for this until da:

function getWeekDaysInMonth(month = 0, year = 2018) {
  console.log('Weekdays for', new Date(year, month, 1).toString())
  return new Array(new Date(year, month+1, 0).getDate()).fill().map((n, i) => {
    const weekDay = new Date(year, month, ++i).getDay();
    return weekDay > 0 && weekDay < 6 && i;
  }).filter(val => !!val);
}

console.log(getWeekDaysInMonth(2, 2018))

Outputs: [1, 2, 5, 6, 7, 8, 9, 12, 13, 14, 15,16,19,20,21,23,26,27,27,28,29,30]

Repl.it Session

Explaining:

First we will have to iterate by the total number of days of the month that is provided, in this case Marco (0 based, then 2) - this loop is made by constructing an array of length equal to the maximum of days of the month that is then filled with "nothing" (via fill() and iterated by map() .

Then we have to see if the day of the week of that date is greater than 0 (Sunday) or 6 (Saturday) and if so, return the day of the month .

Once this mapping is finished, we will filter all non-positive values from the array.

:)

    
10.04.2018 / 16:49
0

I recently had to recover all the Sundays , the Quintas and the Saturdays of the current month to generate a scale. I found the moment-weekdaysin plugin for the Moment. js .

You should run moment passing as a parameter the year and month that the user reports: moment('2018-03')

Next, you should run the weekdaysInMonth method of the moment-weekdaysin plugin , reporting a array with values from 0 to 6 .

0 = Domingo
1 = Segunda
2 = Terça
3 = Quarta
4 = Quinta
5 = Sexta
6 = Sábado

As you only want from Second to Friday will look like this: weekdaysInMonth([1,2,3,4,5])

Example working.

// Define o idioma
moment.locale('pt-br');
let btn = document.querySelector('#btn');
let mes = document.querySelector('#mes');
let ano = document.querySelector('#ano');
const getDaysOfMonth = () => {
  const datas = moment('${ano.value}-${mes.value}').weekdaysInMonth([1,2,3,4,5]);
  datas.forEach(data => console.log(data.format('L')));
};
btn.addEventListener('click', getDaysOfMonth);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment-with-locales.js"></script>
<script src="https://cdn.rawgit.com/kodie/moment-weekdaysin/master/moment-weekdaysin.js"></script><inputtype="number" id="mes" placeholder="Mês" min="1" max="12" value="3">
<input type="number" id="ano" placeholder="Ano" min="1990" max="2050" value="2018">
<button id="btn">OK</button>
    
10.03.2018 / 01:41