JavaScript function to add X months to a date

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

    I wrote this alternative solution which works fine to me. It is useful when you wish calculate the end of a contract. For example, start=2016-01-15, months=6, end=2016-7-14 (i.e. last day - 1):

    
    

    Examples:

    addMonths(new Date("2016-01-01"), 1); // 2016-01-31
    addMonths(new Date("2016-01-01"), 2); // 2016-02-29 (2016 is a leap year)
    addMonths(new Date("2016-01-01"), 13); // 2017-01-31
    addMonths(new Date("2016-01-01"), 14); // 2017-02-28
    

提交回复
热议问题