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

2019-06-04 01:40发布

问题:

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

回答1:

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/



回答2:

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...



回答3:

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
}


标签: momentjs