Home > Enterprise >  Retrieve how many Monday, Tuesday, ... between two dates in Javascript
Retrieve how many Monday, Tuesday, ... between two dates in Javascript

Time:12-06

I need to get in Javascript the number 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 an NPM package or example of the code to do this? I am personally stuck :(

Thanks in advance for your help !

CodePudding user response:

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

CodePudding user response:

I'm not giving the ultimate answer, but here is the answer to get all mondays (answer here https://stackoverflow.com/a/9481478/17978333) :

function getMondays() {
    var d = new Date(),
        month = d.getMonth(),
        mondays = [];

    d.setDate(1);

    // Get the first Monday in the month
    while (d.getDay() !== 1) {
        d.setDate(d.getDate()   1);
    }

    // Get all the other Mondays in the month
    while (d.getMonth() === month) {
        mondays.push(new Date(d.getTime()));
        d.setDate(d.getDate()   7);
    }

    return mondays;
}

You can now make a function for the days you need, and at the end of function push it in your array

  • Related