Is there a way that I get the last monday in the month with moment.js?
I know I can get the end of the month with:
moment().endOf(\'month\')
B
you get always monday with isoweek:
moment().endOf('month').startOf('isoweek')
I made a dropin for this, once you install/add it, so you can do:
moment().endOf('month').subtract(1,'w').nextDay(1)
That code gets the end of the month, minus 1 week, and then the next Monday.
To simplify this, you could do:
days = moment().allDays(1) //=> mondays in the month
days[days.length - 1] //=> last monday
Which gets all the Mondays in the month, and then selects the first one.
You could simplify it further like this:
moment().allDays(1).pop()
But this removes the Monday from the list - but if you aren't using the list (as in the example above), it shouldn't matter. If it does, you might want this:
moment().allDays(1).last()
But it requires a pollyfill:
if (!Array.prototype.last){
Array.prototype.last = function(){
return this[this.length - 1];
};
};
You're almost there. You just need to add a simple loop to step backward day-by-day until you find a Monday:
result = moment().endOf('month');
while (result.day() !== 1) {
result.subtract(1, 'day');
}
return result;
moment().endOf('month').day('Monday')