JavaScript function to add X months to a date

后端 未结 19 2065
星月不相逢
星月不相逢 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:22
    d = new Date();
    
    alert(d.getMonth()+1);
    

    Months have a 0-based index, it should alert(4) which is 5 (may);

    0 讨论(0)
  • 2020-11-22 03:24

    Considering none of these answers will account for the current year when the month changes, you can find one I made below which should handle it:

    The method:

    Date.prototype.addMonths = function (m) {
        var d = new Date(this);
        var years = Math.floor(m / 12);
        var months = m - (years * 12);
        if (years) d.setFullYear(d.getFullYear() + years);
        if (months) d.setMonth(d.getMonth() + months);
        return d;
    }
    

    Usage:

    return new Date().addMonths(2);
    
    0 讨论(0)
  • 2020-11-22 03:25

    Taken from @bmpsini and @Jazaret responses, but not extending prototypes: using plain functions (Why is extending native objects a bad practice?):

    function isLeapYear(year) { 
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
    }
    
    function getDaysInMonth(year, month) {
        return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
    }
    
    function addMonths(date, value) {
        var d = new Date(date),
            n = date.getDate();
        d.setDate(1);
        d.setMonth(d.getMonth() + value);
        d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));
        return d;
    }
    

    Use it:

    var nextMonth = addMonths(new Date(), 1);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 03:27

    This works for all edge cases. The weird calculation for newMonth handles negative months input. If the new month does not match the expected month (like 31 Feb), it will set the day of month to 0, which translates to "end of previous month":

    function dateAddCalendarMonths(date, months) {
        monthSum = date.getMonth() + months;
        newMonth = (12 + (monthSum % 12)) % 12;
        newYear = date.getFullYear() + Math.floor(monthSum / 12);
        newDate = new Date(newYear, newMonth, date.getDate());
        return (newDate.getMonth() != newMonth)
            ? new Date(newDate.setDate(0))
            : newDate;
    }
    
    0 讨论(0)
  • 2020-11-22 03:27
    addDateMonate : function( pDatum, pAnzahlMonate )
    {
        if ( pDatum === undefined )
        {
            return undefined;
        }
    
        if ( pAnzahlMonate === undefined )
        {
            return pDatum;
        }
    
        var vv = new Date();
    
        var jahr = pDatum.getFullYear();
        var monat = pDatum.getMonth() + 1;
        var tag = pDatum.getDate();
    
        var add_monate_total = Math.abs( Number( pAnzahlMonate ) );
    
        var add_jahre = Number( Math.floor( add_monate_total / 12.0 ) );
        var add_monate_rest = Number( add_monate_total - ( add_jahre * 12.0 ) );
    
        if ( Number( pAnzahlMonate ) > 0 )
        {
            jahr += add_jahre;
            monat += add_monate_rest;
    
            if ( monat > 12 )
            {
                jahr += 1;
                monat -= 12;
            }
        }
        else if ( Number( pAnzahlMonate ) < 0 )
        {
            jahr -= add_jahre;
            monat -= add_monate_rest;
    
            if ( monat <= 0 )
            {
                jahr = jahr - 1;
                monat = 12 + monat;
            }
        }
    
        if ( ( Number( monat ) === 2 ) && ( Number( tag ) === 29 ) )
        {
            if ( ( ( Number( jahr ) % 400 ) === 0 ) || ( ( Number( jahr ) % 100 ) > 0 ) && ( ( Number( jahr ) % 4 ) === 0 ) )
            {
                tag = 29;
            }
            else
            {
                tag = 28;
            }
        }
    
        return new Date( jahr, monat - 1, tag );
    }
    
    
    testAddMonate : function( pDatum , pAnzahlMonate )
    {
        var datum_js = fkDatum.getDateAusTTMMJJJJ( pDatum );
        var ergebnis = fkDatum.addDateMonate( datum_js, pAnzahlMonate );
    
        app.log( "addDateMonate( \"" + pDatum + "\", " + pAnzahlMonate + " ) = \"" + fkDatum.getStringAusDate( ergebnis ) + "\"" );
    },
    
    
    test1 : function()
    {
        app.testAddMonate( "15.06.2010",    10 );
        app.testAddMonate( "15.06.2010",   -10 );
        app.testAddMonate( "15.06.2010",    37 );
        app.testAddMonate( "15.06.2010",   -37 );
        app.testAddMonate( "15.06.2010",  1234 );
        app.testAddMonate( "15.06.2010", -1234 );
        app.testAddMonate( "15.06.2010",  5620 );
        app.testAddMonate( "15.06.2010", -5120 );
    
    }
    
    0 讨论(0)
提交回复
热议问题