JavaScript function to add X months to a date

后端 未结 19 2336
星月不相逢
星月不相逢 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条回答
  •  Happy的楠姐
    2020-11-22 03:10

    This function handles edge cases and is fast:

    function addMonthsUTC (date, count) {
      if (date && count) {
        var m, d = (date = new Date(+date)).getUTCDate()
    
        date.setUTCMonth(date.getUTCMonth() + count, 1)
        m = date.getUTCMonth()
        date.setUTCDate(d)
        if (date.getUTCMonth() !== m) date.setUTCDate(0)
      }
      return date
    }
    

    test:

    > d = new Date('2016-01-31T00:00:00Z');
    Sat Jan 30 2016 18:00:00 GMT-0600 (CST)
    > d = addMonthsUTC(d, 1);
    Sun Feb 28 2016 18:00:00 GMT-0600 (CST)
    > d = addMonthsUTC(d, 1);
    Mon Mar 28 2016 18:00:00 GMT-0600 (CST)
    > d.toISOString()
    "2016-03-29T00:00:00.000Z"
    

    Update for non-UTC dates: (by A.Hatchkins)

    function addMonths (date, count) {
      if (date && count) {
        var m, d = (date = new Date(+date)).getDate()
    
        date.setMonth(date.getMonth() + count, 1)
        m = date.getMonth()
        date.setDate(d)
        if (date.getMonth() !== m) date.setDate(0)
      }
      return date
    }
    

    test:

    > d = new Date(2016,0,31);
    Sun Jan 31 2016 00:00:00 GMT-0600 (CST)
    > d = addMonths(d, 1);
    Mon Feb 29 2016 00:00:00 GMT-0600 (CST)
    > d = addMonths(d, 1);
    Tue Mar 29 2016 00:00:00 GMT-0600 (CST)
    > d.toISOString()
    "2016-03-29T06:00:00.000Z"
    

提交回复
热议问题