【问题标题】:javascript add month to date [duplicate]javascript添加月至今[重复]
【发布时间】:2013-03-07 12:19:22
【问题描述】:

我想将 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);
    }

【问题讨论】:

  • 您是否尝试过在 new Date() 调用中增加月份值? var terminDate = new Date(parseInt(year),parseInt(month)+monthToAdd, parseInt(day));
  • 修正了月份的重构版本,以防您发现它有用jsfiddle.net/LRA7d/2
  • 不需要parseInt(year)parseInt(month)等。鉴于在每种情况下都省略了基数,最好使用普通的yearmonth等。

标签: javascript


【解决方案1】:

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;

【讨论】:

  • 是的,我明白了,这会将 12 月显示为 12 而不是 0。+1
【解决方案2】:

您应该使用javascript Date 对象的本地方法来更新它。例如,查看此问题已接受的答案,这是解决问题的正确方法。

Javascript function to add X months to a date

【讨论】:

    【解决方案3】:

    函数可以更简洁地写成:

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

    terminbismonthToAdd 的值应在使用前进行验证,从该值生成的日期也应验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-21
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多