简体   繁体   中英

Get last monday in month in moment.js

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

But how about the last monday?

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;

你总是星期一与isoweek

moment().endOf('month').startOf('isoweek')
moment().endOf('month').day('Monday')

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];
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM