2

I need to get in Javascript the numbers of Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday between two dates.

For example, between 01/12/2022 and 31/12/2022 :

[{dayOfTheWeek: "Monday", nbOf: 4}, {dayOfTheWeek: "Tuesday", nbOf: 4}, {dayOfTheWeek: "Wednesday", nbOf: 4}, {dayOfTheWeek: "Thursday", nbOf: 5}, {dayOfTheWeek: "Friday", nbOf: 5}, {dayOfTheWeek: "Saturday", nbOf: 5}, {dayOfTheWeek: "Sunday", nbOf: 5}]

Is there a NPM package or example of the code to do this? I am personally stuck :(

Thanks in advance for your help!

cucurbit
  • 1,422
  • 1
  • 13
  • 32
Sabgramar
  • 101
  • 5
  • Does this answer your question? [Calculate number of specific weekdays between dates](https://stackoverflow.com/questions/25562173/calculate-number-of-specific-weekdays-between-dates) – Marios Dec 06 '22 at 10:49

1 Answers1

1

One approach to this would be to calculate the number of complete weeks between the two dates and then work out the extra days over that period in order to calculate which days there are a higher count. Something like the following should help here:

function getDayCount(startDate, endDate) { // Assumes startDate and endDate are Date objects
  const msInDay = 86400000;
  const dayCount = (endDate - startDate) / msInDay + 1; // Plus one to make inclusive of start and end date
  const completeWeeks = Math.floor(dayCount / 7);
  const extraDays = dayCount % 7;
  
  return Object.keys(daysOfWeek).map(dayOfTheWeek => {
    const dayNumber = daysOfWeek[dayOfTheWeek];
    const firstExtraDay = startDate.getDay();
    const lastExtraDay = (startDate.getDay() + extraDays - 1) % 7;
    const isExtraDay = (dayNumber >= firstExtraDay && dayNumber <= lastExtraDay)
      || (dayNumber <= lastExtraDay - 7);
    
    let nbOf = completeWeeks;
    if (extraDays > 0 && isExtraDay) {
      nbOf++;
    }
    
    return {
      dayOfTheWeek, 
      nbOf 
    };
  });
}

const daysOfWeek = {
  Monday: 1,
  Tuesday: 2,
  Wednesday: 3,
  Thursday: 4,
  Friday: 5,
  Saturday: 6,
  Sunday: 0
};

console.log(getDayCount(new Date('2022/12/1'), new Date('2022/12/31')));
Bladeski
  • 371
  • 2
  • 10
  • That's what I wanted, thanks ! – Sabgramar Dec 06 '22 at 12:36
  • "const lastExtraDay = (startDate.getDay() + extraDays - 1) % 7;" Is "% 7" really usefull ? "const lastExtraDay = startDate.getDay() + extraDays - 1" Isn't enough ? – Sabgramar Dec 06 '22 at 12:59
  • 1
    The modulo is needed. Example: startDate is a Saturday and there are 13 days in total... `lastExtraDay = 6 + 6 - 1` equates to 11, which isn't a valid day. With the modulo (remainder) we get lastExtraDay being 4, which is Thursday (13 days from Saturday). – Bladeski Dec 06 '22 at 14:11