0

I want to get the Monday list from the current week to the next five Mondays. I tried getting it for the current month. But if the date is the last of the month and it should give that Monday date and next five mondays date.

here is the code I tried.

var Mondays = [];
var month = new Date().getMonth();
while (d.getMonth() === month) {
    mondays.push(new Date(d.getTime()));
    d.setDate(d.getDate() + 7);
}
return mondays

the above will return the current month mondays. can someone help me out please.

Thanks in advance.

chaitanya
  • 352
  • 4
  • 14

1 Answers1

1

function isDate(type) {
  return (/^\[object\s+Date\]$/).test(
    Object.prototype.toString.call(type)
  );
}

function getAllMondaysFromDate(count, date) {
  count = parseInt(count, 10);
  count = Number.isNaN(count)
    ? 1
    // prevent negative counts and limit counting to
    // approximately 200 years into a given date's future.
    : Math.min(Math.max(count, 0), 10436);

  // do not mutate the date in case it was provided.
  // thanks to RobG for pointing to it.
  date = (isDate(date) && new Date(date.getTime())) || new Date();

  const listOfMondayDates = [];
  const mostRecentMondayDelta = ((date.getDay() + 6) % 7);

  date.setDate(date.getDate() - mostRecentMondayDelta);

  while (count--) {
    date.setDate(date.getDate() + 7);

    listOfMondayDates.push(
      new Date(date.getTime())
    );
  }
  return listOfMondayDates;
}

// default ...
console.log(
  'default ...',
  getAllMondaysFromDate()
);

// the next upcoming 5 mondays from today ...
console.log(
  'the next upcoming 5 mondays from today ...',
  getAllMondaysFromDate(5)
    .map(date => date.toString())
);

// the next 3 mondays following the day of two weeks ago ...
console.log(
  'the next 3 mondays following the day of two weeks ago ...',
  getAllMondaysFromDate(3, new Date(Date.now() - (14 * 24 * 3600000)))
    .map(date => date.toString())
);

// proof for not mutating the passed date reference ...
const dateNow = new Date(Date.now());

console.log(
  'proof for not mutating the passed date reference ...\n',
  'before :: dateNow :',
  dateNow
);
console.log(
  'invoke with `dateNow`',
  getAllMondaysFromDate(dateNow)
);
console.log(
  'proof for not mutating the passed date reference ...\n',
  'after :: dateNow :',
  dateNow
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37