JavaScript function to add X months to a date

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

    This works for all edge cases. The weird calculation for newMonth handles negative months input. If the new month does not match the expected month (like 31 Feb), it will set the day of month to 0, which translates to "end of previous month":

    function dateAddCalendarMonths(date, months) {
        monthSum = date.getMonth() + months;
        newMonth = (12 + (monthSum % 12)) % 12;
        newYear = date.getFullYear() + Math.floor(monthSum / 12);
        newDate = new Date(newYear, newMonth, date.getDate());
        return (newDate.getMonth() != newMonth)
            ? new Date(newDate.setDate(0))
            : newDate;
    }
    

提交回复
热议问题