Get last monday in month in moment.js

前端 未结 4 1466
梦毁少年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:52

    you get always monday with isoweek:

    moment().endOf('month').startOf('isoweek')
    
    0 讨论(0)
  • 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];
        };
    };
    
    0 讨论(0)
  • 2021-01-12 07:04

    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;
    
    0 讨论(0)
  • 2021-01-12 07:15
    moment().endOf('month').day('Monday')
    
    0 讨论(0)
提交回复
热议问题