Skip to content

Instantly share code, notes, and snippets.

@guibranco
Last active April 24, 2021 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guibranco/dad02fc3e4caf8be98404f975a07083a to your computer and use it in GitHub Desktop.
Save guibranco/dad02fc3e4caf8be98404f975a07083a to your computer and use it in GitHub Desktop.
Exibe quantos dias da semana tem entre duas datas - Facebook - NodeJS Brasil - https://www.facebook.com/groups/1407602962733165/permalink/2136557383171049
var startDate = new Date(2021, 3, 1);
var endDate = new Date(2021, 4, 1);
var diffTime = Math.abs(endDate - startDate);
var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
var totalWeeks = Math.round(diffDays / 7);
var remainingDays = diffDays % 7;
//se quiser considerar o dia final também, descomente a linha abaixo:
//remainingDays++;
console.warn(`Semanas cheias: ${totalWeeks}`);
console.warn(`Dias sobrando: ${remainingDays}`);
console.group('Dias');
var weekDays = [];
for(var i = 0; i < 7; i++)
weekDays[i] = totalWeeks;
var startDay = startDate.getDay();
for(var i = 0; i < remainingDays; i++){
var currentWeekDay = startDay + i;
if(currentWeekDay > 6)
currentWeekDay -= 6;
weekDays[currentWeekDay]++;
}
var weekDaysNames = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];
for(var i = 0; i < 7; i++)
console.log(`${weekDaysNames[i]}: ${weekDays[i]} dia${(weekDays[i] == 1 ? '' : 's')}`);
console.groupEnd();
@guibranco
Copy link
Author

Este exemplo não conta o dia final, visto que nesse caso o dia final é as 00:00, logo não entra na conta, se quiser contar o dia final inclusive, basta somar 1 ao remainingDays como na linha 11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment