JavaScript function to add X months to a date

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

    All these seem way too complicated and I guess it gets into a debate about what exactly adding "a month" means. Does it mean 30 days? Does it mean from the 1st to the 1st? From the last day to the last day?

    If the latter, then adding a month to Feb 27th gets you to March 27th, but adding a month to Feb 28th gets you to March 31st (except in leap years, where it gets you to March 28th). Then subtracting a month from March 30th gets you... Feb 27th? Who knows...

    For those looking for a simple solution, just add milliseconds and be done.

    function getDatePlusDays(dt, days) {
      return new Date(dt.getTime() + (days * 86400000));
    }
    

    or

    Date.prototype.addDays = function(days) {
      this = new Date(this.getTime() + (days * 86400000));
    };
    

提交回复
热议问题