javascript 添加月至今日

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15271094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:07:46  来源:igfitidea点击:

javascript add month to date

javascript

提问by krackmoe

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?

我想将 1 个月或 6 个月添加到给定日期。但如果我加一个月,年份不会增加。如果我将 6 个月添加到 6 月,我会返回 00 月,但年份会增加。你能帮我一下吗?

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);
    }

回答by Prasath K

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

getMonth 返回一个从 0 到 11 的数字,这意味着一月为 0,二月为 1 ......等等

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;

回答by RobG

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 terminbisand monthToAddshould be validated before use, as should the date generated from the value.

和的值应在使用前验证,从值生成的日期terminbismonthToAdd应验证。

回答by Korijn

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 Date 对象的本机方法来更新它。例如,查看此问题的已接受答案,这是解决您问题的正确方法。

Javascript function to add X months to a date

将 X 个月添加到日期的 Javascript 函数