JavaScript function to add X months to a date

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

    As most of the answers highlighted, we could use setMonth() method together with getMonth() method to add specific number of months to a given date.

    Example: (as mentioned by @ChadD in his answer. )

    var x = 12; //or whatever offset 
    var CurrentDate = new Date();
    CurrentDate.setMonth(CurrentDate.getMonth() + x);
    

    But we should carefully use this solution as we will get trouble with edge cases.

    To handle edge cases, answer which is given in following link is helpful.

    https://stackoverflow.com/a/13633692/3668866

提交回复
热议问题