Get last monday in month in moment.js

前端 未结 4 1494
梦毁少年i
梦毁少年i 2021-01-12 06:51

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

4条回答
  •  爱一瞬间的悲伤
    2021-01-12 06:59

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

提交回复
热议问题