How to get monday of the week which overlaps 2 months using moment js?

Maybe too late, but it could be helpful for future viewers.

The function takes start and end, but we only use end, so you can get rid of start as all the operations will be on end date in order to get the last monday. To achieve our goal we need to do two simple steps:

  1. Get the end of the month with the end date.
  2. Get the monday of the previous “calculated” date.

For the first step, we use End of Time in order to get the end of the month (the last day).

Mutates the original moment by setting it to the end of a unit of time.

Then we can get the Monday of the week the date is, and we can use Date of Week with the date of previous step.

Gets or sets the day of the week. […] As of 2.1.0, a day name is also supported. This is parsed in the moment’s current locale.

And taking your examples, we can test our function:

function lastMonday(start, end) {
  console.log('Start is ', moment(start).format('LL'));
  console.log('End is ', moment(end).format('LL'));
  return moment(end).endOf('month').day('Monday');

console.log('Last monday is', lastMonday('2020-09-01', '2020-09-30').format('LL'));
console.log('Last monday is', lastMonday('2020-10-01', '2020-10-31').format('LL'));
console.log('Last monday is', lastMonday('2020-11-01', '2020-11-30').format('LL'));
console.log('Last monday is', lastMonday('2020-11-01', '2020-12-31').format('LL'));
<script src=""></script>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top