How many days of the week do you have in the month? [closed]
want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 6 months ago .
improve this questionHello, good night!
I did a lot of research on the internet and found nothing concerning this doubt! I would like to get how many days of the week there is within a month using javascript! Example:
Quantos sábados existe no mês de atual? = 5
Quantas terças-feiras existes no mês atual? = 4
I would like a script where it would tell me the number of days that exists in the current month.
Thank you right now...
2 answers
I made a library to generate dates, Week number etc that I use in my projects, can be useful to you.
In this case it's simple and you can do it in JavaScript. Note that this script is insensitive to holidays :), you have to add this logic by hand.
function getWorkingDays(month) {
const date = new Date(2020, month, 1, 0, 0, 0);
let workingdays = 0;
while (month === date.getMonth()) {
const currentDay = date.getDay();
const isWeekend = (currentDay === 6) || (currentDay === 0);
if (!isWeekend) workingdays++; // se não é fds aumentar o nr
date.setDate(date.getDate() + 1); // testar o próximo dia
}
return workingdays;
}
// lembra-te que meses têm base 0
// ou seja: janeiro é o mes 0, fevereiro o mes 1, etc...
console.log(getWorkingDays(0));
console.log(getWorkingDays(1));
To know the number of specific days you can make an adaptation of the Code:
function getDaysByType(month, type) {
const date = new Date(2020, month, 1, 0, 0, 0);
let count = 0;
while (month === date.getMonth()) {
if (date.getDay() === type) count++;
date.setDate(date.getDate() + 1); // testar o próximo dia
}
return count;
}
// sábado tem o nr 6
// domingo tem o nr 0
// segunda tem o nr 1
// etc
console.log(getDaysByType(0, 0));
console.log(getDaysByType(0, 1));
console.log(getDaysByType(0, 2));
console.log(getDaysByType(0, 3));
console.log(getDaysByType(0, 4));
console.log(getDaysByType(0, 5));
console.log(getDaysByType(0, 6));
Using a while summing days until solves the problem:
while (month === date.getMonth()) {
if (date.getDay() === type) count++;
date.setDate(date.getDate() + 1); // testar o próximo dia
}
But the increment of date.getDate() + 1
will generate increments and on average 30 loops , most of which are unnecessary, if the required rule is a specific day of the Week just add +7
inside the loop instead of +1
and check if it is the same month later and then yes do the sum count++
, the function a little optimized can be like this (as the test done at the end of the answer was almost 3 times more Fast):
function getDaysByType(type, month, year) {
const date = new Date(year ? year : new Date().getFullYear(), month, 1, 0, 0, 0);
var count = 0, increment = 1;
while (month === date.getMonth()) {
if (date.getDay() === type) {
count++;
increment = 7;
}
date.setDate(date.getDate() + increment); // testar o próximo dia
}
return count;
}
console.log('Quantidade de Sábados em Janeiro:', getDaysByType(0, 0));
console.log('Quantidade de Sábados em Fevereiro:', getDaysByType(0, 1));
console.log('Quantidade de Sábados em Março:', getDaysByType(0, 2));
console.log('Quantidade de Sábados em Abril:', getDaysByType(0, 3));
console.log('Quantidade de Sábados em Maio:', getDaysByType(0, 4));
console.log('Quantidade de Sábados em Junho:', getDaysByType(0, 5));
console.log('Quantidade de Sábados em Julho:', getDaysByType(0, 6));
This way will be 4-11 loops instead of 28-31 loops, which made ~70% faster.
However I have another proposal, use the basic math, because if we know that a day of the week can appear between 4 and 5 times in the same month with this we already have how to get by a calculation, we will only need to know which the first day of the week of a month and which]}
This way got ~90% faster :
Remembering that 0 = Saturday, 1 = Sunday, 2 = Monday, 3 = Tuesday, 4 = Wednesday, 5 = Thursday, 6 = Friday
Month from 0 (January) to 11 (December)
function sumWeekDaysInMonth(weekday, month, year)
{
if (!year) year = new Date().getFullYear();
// Obtem o ultimo dia do mês
var daysInMonth = new Date(year, month + 1, 0).getDate();
// Obtem primeiro dia da semana do mês
var firstWeekDay = new Date(year, month, 1).getDay();
return Math.floor((daysInMonth + (weekday + firstWeekDay) % 7) / 7);
}
console.log('Quantidade de Sábados em Janeiro (ano atual):', sumWeekDaysInMonth(6, 0));
console.log('Quantidade de Sábados em Fevereiro (ano atual):', sumWeekDaysInMonth(6, 1));
console.log('Quantidade de Sábados em Março (ano atual):', sumWeekDaysInMonth(6, 2));
console.log('----');
console.log('Quantidade de Sábados em Janeiro 1988:', sumWeekDaysInMonth(6, 0, 1988));
console.log('Quantidade de Sábados em Fevereiro 1988:', sumWeekDaysInMonth(6, 1, 1988));
console.log('Quantidade de Sábados em Março 1988:', sumWeekDaysInMonth(6, 2, 1988));
To better understand, we use % to get what's left in a division, SO:
Day of the week + first day of the week of the month / total days Week (7)
In January was (6 + 3) % 7 = 2 (it would be like 6+3=9 and 9/7=1,2, rounding gets 2)
Then add the number of days in the month and divide by 7, 4 was the remaining result of the Division:
(31 + 2) / 7 = 4,714285714285714
Then uses
Math.floor()
to return the smallest integer that will be " 4 " for the month of January 2020
See the benchmark for All codes: https://jsbench.me/lwkdh223r9/1
-
With optimized while managed to run almost 3 times faster
-
With "math" was the faster performing almost 10 times faster