javascript 添加月份至今

标签 javascript

我想向给定日期添加 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);
    }

最佳答案

getMonth 返回 0 到 11 之间的数字,这意味着 0 代表一月,1 代表二月......等等

这样修改

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

month = terminDate.getMonth() + 1;

关于javascript 添加月份至今,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15271094/

相关文章:

javascript - 如何从特定选定行的事件发送者数据中获取模型数据?

javascript - google.maps.places.Autocomplete 无法使用 SimpleHTTPServer

javascript - Firefox 和 ie11 中的多点触控支持

javascript - 正则表达式:我还应该使用其他东西来实现我想要的吗?

javascript - 单击事件在 svg 路径上不起作用

javascript - 将 emojione img html 标签转换回 unicode

javascript - Angular.js 将错误消息从服务传递到 Controller $scope

javascript - react native : Accessing values in returned object: undefined

javascript - d3.js 气泡图中的中心图像

javascript - 在多个 PHP 页面上使用来自 AJAX 函数的填充变量更新 SQL 查询