JavaScript function to add X months to a date

后端 未结 19 2069
星月不相逢
星月不相逢 2020-11-22 02:44

I’m looking for the easiest, cleanest way to add X months to a JavaScript date.

I’d rather not handle the rolling over of the year or have to write my own function.<

19条回答
  •  一向
    一向 (楼主)
    2020-11-22 03:24

    Considering none of these answers will account for the current year when the month changes, you can find one I made below which should handle it:

    The method:

    Date.prototype.addMonths = function (m) {
        var d = new Date(this);
        var years = Math.floor(m / 12);
        var months = m - (years * 12);
        if (years) d.setFullYear(d.getFullYear() + years);
        if (months) d.setMonth(d.getMonth() + months);
        return d;
    }
    

    Usage:

    return new Date().addMonths(2);
    

提交回复
热议问题