Get last monday in month in moment.js

人盡茶涼 提交于 2020-01-21 06:49:06

问题


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?


回答1:


you get always monday with isoweek:

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



回答2:


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;



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/25126829/get-last-monday-in-month-in-moment-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!