Get the last Monday of the month at moment.js

Is there any way that I get the last Monday of the month using the .js moment?

I know I can finish at the end of the month: moment().endOf('month')

But what about the last Monday?

+6
source share
4 answers

You will always be on Monday with isoweek :

 moment().endOf('month').startOf('isoweek') 
+7
source

You are almost there. You just need to add a simple loop to step back day after day until you find Monday:

 result = moment().endOf('month'); while (result.day() !== 1) { result.subtract(1, 'day'); } return result; 
+13
source
 moment().endOf('month').day('Monday') 
+1
source

I made a dropin for this as soon as you installed / added it so you can:

 moment().endOf('month').subtract(1,'w').nextDay(1) 

This code gets the end of the month, minus 1 week, and then next Monday.

To simplify this, you can do:

 days = moment().allDays(1) //=> mondays in the month days[days.length - 1] //=> last monday 

who receives all Mondays a month, and then selects the first.

You can simplify it as follows:

 moment().allDays(1).pop() 

But this removes Monday from the list, but if you do not use the list (as in the example above), it does not matter. If so, you may want this:

 moment().allDays(1).last() 

But this requires pollyfill:

 if (!Array.prototype.last){ Array.prototype.last = function(){ return this[this.length - 1]; }; }; 
0
source

Source: https://habr.com/ru/post/973341/


All Articles