In Moment.js, how do you get the date of the next

2019-06-04 01:41发布

Examples:

  • NOW it's March 26th 2012. I ask for next February. It should return 2013-01-01
  • NOW it's March 26th 2012. I ask for next April. It should return 2012-04-01

标签: momentjs
3条回答
贼婆χ
2楼-- · 2019-06-04 02:03

Next January 1st: moment().month(0+12).date(1).hour(0).minute(0).second(0)

Next March 17th: moment().month(2).date(17).hour(0).minute(0).second(0)

edit: you just need to pay attention to whether the created date is less than now. Since it's currently february, getting next january needs to add 12 months, but getting next march doesn't.

function getNextJan(){
    var j = moment().month(0).date(1).hour(0).minute(0).second(0)
    if(j < moment()) return j.month(12)
    return j
}
查看更多
走好不送
3楼-- · 2019-06-04 02:20

You could do something like this.

// date is a JS date or moment
// month is the zero indexed month (0 - 11)
function nextMonth(date, month) {
    var input = moment(date);
    var output = input.clone().startOf('month').month(month);
    return output > input ? output : output.add(1, 'years');
}

See the documentation on manipulating a moment. http://momentjs.com/docs/#/manipulating/

查看更多
爷的心禁止访问
4楼-- · 2019-06-04 02:20

Wrote this:

    /**
        @var date is a JS date or moment
        @var month is the month in the 0-11 format
     */
    var getNextMonthOccurrence: function(date, month){
        var m = moment(date);

        var this_year = new Date(m.year(), month, 1);
        var next_year = new Date(m.year() + 1, month, 1);

        return this_year > m ? this_year : next_year;
    }

But there's got to be a better way of doing it...

查看更多
登录 后发表回答