JavaScript function to add X months to a date

后端 未结 19 2074
星月不相逢
星月不相逢 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:09

    I changed the accepted answer a bit to keep the original date intact, as I think it should in a function like this.

    function addMonths(date, months) {
        let newDate = new Date(date);
        var day = newDate.getDate();
        newDate.setMonth(newDate.getMonth() + +months);
        if (newDate.getDate() != day)
            newDate.setDate(0);
        return newDate;
    }

提交回复
热议问题