JavaScript function to add X months to a date

后端 未结 19 2087
星月不相逢
星月不相逢 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));
    };
    
    0 讨论(0)
  • 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):

    <script>
    function daysInMonth(year, month)
    {
        return new Date(year, month + 1, 0).getDate();
    }
    
    function addMonths(date, months)
    {
        var target_month = date.getMonth() + months;
        var year = date.getFullYear() + parseInt(target_month / 12);
        var month = target_month % 12;
        var day = date.getDate();
        var last_day = daysInMonth(year, month);
        if (day > last_day)
        {
            day = last_day;
        }
        var new_date = new Date(year, month, day);
        return new_date;
    }
    
    var endDate = addMonths(startDate, months);
    </script>
    

    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
    
    0 讨论(0)
  • 2020-11-22 03:07

    From the answers above, the only one that handles the edge cases (bmpasini's from datejs library) has an issue:

    var date = new Date("03/31/2015");
    var newDate = date.addMonths(1);
    console.log(newDate);
    // VM223:4 Thu Apr 30 2015 00:00:00 GMT+0200 (CEST)
    

    ok, but:

    newDate.toISOString()
    //"2015-04-29T22:00:00.000Z"
    

    worse :

    var date = new Date("01/01/2015");
    var newDate = date.addMonths(3);
    console.log(newDate);
    //VM208:4 Wed Apr 01 2015 00:00:00 GMT+0200 (CEST)
    newDate.toISOString()
    //"2015-03-31T22:00:00.000Z"
    

    This is due to the time not being set, thus reverting to 00:00:00, which then can glitch to previous day due to timezone or time-saving changes or whatever...

    Here's my proposed solution, which does not have that problem, and is also, I think, more elegant in that it does not rely on hard-coded values.

    /**
    * @param isoDate {string} in ISO 8601 format e.g. 2015-12-31
    * @param numberMonths {number} e.g. 1, 2, 3...
    * @returns {string} in ISO 8601 format e.g. 2015-12-31
    */
    function addMonths (isoDate, numberMonths) {
        var dateObject = new Date(isoDate),
            day = dateObject.getDate(); // returns day of the month number
    
        // avoid date calculation errors
        dateObject.setHours(20);
    
        // add months and set date to last day of the correct month
        dateObject.setMonth(dateObject.getMonth() + numberMonths + 1, 0);
    
        // set day number to min of either the original one or last day of month
        dateObject.setDate(Math.min(day, dateObject.getDate()));
    
        return dateObject.toISOString().split('T')[0];
    };
    

    Unit tested successfully with:

    function assertEqual(a,b) {
        return a === b;
    }
    console.log(
        assertEqual(addMonths('2015-01-01', 1), '2015-02-01'),
        assertEqual(addMonths('2015-01-01', 2), '2015-03-01'),
        assertEqual(addMonths('2015-01-01', 3), '2015-04-01'),
        assertEqual(addMonths('2015-01-01', 4), '2015-05-01'),
        assertEqual(addMonths('2015-01-15', 1), '2015-02-15'),
        assertEqual(addMonths('2015-01-31', 1), '2015-02-28'),
        assertEqual(addMonths('2016-01-31', 1), '2016-02-29'),
        assertEqual(addMonths('2015-01-01', 11), '2015-12-01'),
        assertEqual(addMonths('2015-01-01', 12), '2016-01-01'),
        assertEqual(addMonths('2015-01-01', 24), '2017-01-01'),
        assertEqual(addMonths('2015-02-28', 12), '2016-02-28'),
        assertEqual(addMonths('2015-03-01', 12), '2016-03-01'),
        assertEqual(addMonths('2016-02-29', 12), '2017-02-28')
    );
    
    0 讨论(0)
  • 2020-11-22 03:09

    The following is an example of how to calculate a future date based on date input (membershipssignup_date) + added months (membershipsmonths) via form fields.

    The membershipsmonths field has a default value of 0

    Trigger link (can be an onchange event attached to membership term field):

    <a href="#" onclick="calculateMshipExp()"; return false;">Calculate Expiry Date</a>
    
    function calculateMshipExp() {
    
    var calcval = null;
    
    var start_date = document.getElementById("membershipssignup_date").value;
    var term = document.getElementById("membershipsmonths").value;  // Is text value
    
    var set_start = start_date.split('/');  
    
    var day = set_start[0];  
    var month = (set_start[1] - 1);  // January is 0 so August (8th month) is 7
    var year = set_start[2];
    var datetime = new Date(year, month, day);
    var newmonth = (month + parseInt(term));  // Must convert term to integer
    var newdate = datetime.setMonth(newmonth);
    
    newdate = new Date(newdate);
    //alert(newdate);
    
    day = newdate.getDate();
    month = newdate.getMonth() + 1;
    year = newdate.getFullYear();
    
    // This is British date format. See below for US.
    calcval = (((day <= 9) ? "0" + day : day) + "/" + ((month <= 9) ? "0" + month : month) + "/" + year);
    
    // mm/dd/yyyy
    calcval = (((month <= 9) ? "0" + month : month) + "/" + ((day <= 9) ? "0" + day : day) + "/" + year);
    
    // Displays the new date in a <span id="memexp">[Date]</span> // Note: Must contain a value to replace eg. [Date]
    document.getElementById("memexp").firstChild.data = calcval;
    
    // Stores the new date in a <input type="hidden" id="membershipsexpiry_date" value="" name="membershipsexpiry_date"> for submission to database table
    document.getElementById("membershipsexpiry_date").value = calcval;
    }
    
    0 讨论(0)
  • 2020-11-22 03:09

    I changed the accepted answer a bit to keep the original date intact, as I think it should in a function like this.

    function addMonths(date, months) {
        let newDate = new Date(date);
        var day = newDate.getDate();
        newDate.setMonth(newDate.getMonth() + +months);
        if (newDate.getDate() != day)
            newDate.setDate(0);
        return newDate;
    }

    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题