0

I want to add 1 Month or 6 Month to a given Date. But if i add one Month, the year isnt incremented. And if i add 6 Month to June, i got the Month 00 returned BUT the year is incremented. Could you please help me out?

function addToBis(monthToAdd){
        var tmp = $("#terminbis").val().split('.');

        var day = tmp[0];
        var month = tmp[1];
        var year = tmp[2];

        var terminDate = new Date(parseInt(year),parseInt(month), parseInt(day));
        terminDate.setMonth(terminDate.getMonth()+monthToAdd);

        day = "";
        month = "";
        year = "";

        if(terminDate.getDate() < 10){
            day = "0"+terminDate.getDate();
        } else{
            day = terminDate.getDate();
        }

        if(terminDate.getMonth() < 10){
            month = "0"+terminDate.getMonth();
        } else{
            month = terminDate.getMonth();
        }

        year = terminDate.getFullYear();


        $("#terminbis").val(day+"."+month+"."+year);
    }
krackmoe
  • 1,743
  • 7
  • 29
  • 53
  • have you tried increasing the month value inside the new Date() call? `var terminDate = new Date(parseInt(year),parseInt(month)+monthToAdd, parseInt(day));` – Jeff Shaver Mar 07 '13 at 12:23
  • check:http://stackoverflow.com/questions/5645058/how-to-add-months-to-a-date-in-javascript – Amrendra Mar 07 '13 at 12:25
  • 1
    Refactored version with the months fixed in case you'd find it useful http://jsfiddle.net/LRA7d/2/ – Fabrício Matté Mar 07 '13 at 12:44
  • There is no need for `parseInt(year)`, `parseInt(month)`, etc. Given that the radix is omitted in each case, it's far better to use plain `year`, `month`, etc. – RobG Mar 07 '13 at 13:02

3 Answers3

2

getMonth returns a number from 0 to 11 which means 0 for January , 1 for february ...etc

so modify like this

var terminDate = new Date(parseInt(year),parseInt(month - 1), parseInt(day));
    terminDate.setMonth(terminDate.getMonth()+monthToAdd);

and

month = terminDate.getMonth() + 1;
Prasath K
  • 4,950
  • 7
  • 23
  • 35
0

You should use the javascript Date object's native methods to update it. Check out this question's accepted answer for example, it is the correct approach to your problem.

Javascript function to add X months to a date

Community
  • 1
  • 1
Korijn
  • 1,383
  • 9
  • 27
0

The function can be written much more concisely as:

function addToBis(monthToAdd){

    function z(n) {return (n<10? '0':'') + n}

    var tmp = $("#terminbis").val().split('.');
    var d = new Date(tmp[2], --tmp[1], tmp[0]);

    d.setMonth(d.getMonth() + monthToAdd);

    $("#terminbis").val(z(d.getDate()) + '.' + z(d.getMonth() + 1)
                       + '.' + d.getFullYear();
}

The value of terminbis and monthToAdd should be validated before use, as should the date generated from the value.

RobG
  • 142,382
  • 31
  • 172
  • 209