JavaScript function to add X months to a date

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

    Just to add on to the accepted answer and the comments.

    var x = 12; //or whatever offset
    var CurrentDate = new Date();
    
    //For the very rare cases like the end of a month
    //eg. May 30th - 3 months will give you March instead of February
    var date = CurrentDate.getDate();
    CurrentDate.setDate(1);
    CurrentDate.setMonth(CurrentDate.getMonth()+X);
    CurrentDate.setDate(date);
    

提交回复
热议问题