将天数添加到 jQuery 中的给定日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23854154/
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-08-27 02:23:45  来源:igfitidea点击:

Adding days to given date in jQuery

jquerydate

提问by Cosmin

I have a form with three fields, "start_date", "days", "end_date". I would like to get the end date by adding days to the start date.

我有一个包含三个字段的表单,“start_date”、“days”、“end_date”。我想通过将天数添加到开始日期来获得结束日期。

My jQuery code is:

我的 jQuery 代码是:

$("#days").change(function(){
  var start_date = new Date($("#start_date").attr('value'));
  var days = parseInt($("#days").attr('value'))-1;
  var end_date = new Date(start_date);
  end_date.setDate(start_date.getDate() + days);                            
  $("#end_date").val(end_date.getFullYear() + '-' + ("0" + (end_date.getMonth() + 1)).slice(-2) + '-' + ("0" + end_date.getDate()).slice(-2));
});

In the "end_date" field I get "NaN-aN-aN".

在“end_date”字段中,我得到“NaN-aN-aN”。

What am I doing wrong?

我究竟做错了什么?

回答by William George

NaN stands for Not a Number- This means that the users input is invalid.

NaN 代表Not a Number- 这意味着用户输入无效。

You could check to see if the input is valid by using if(!isNaN(date.getTime())){

您可以使用以下命令检查输入是否有效 if(!isNaN(date.getTime())){

Some code to get you started:

一些帮助您入门的代码:

;(function($, window, document, undefined){
    $("#days").on("change", function(){
       var date = new Date($("#start_date").val()),
           days = parseInt($("#days").val(), 10);

        if(!isNaN(date.getTime())){
            date.setDate(date.getDate() + days);

            $("#end_date").val(date.toInputFormat());
        } else {
            alert("Invalid Date");  
        }
    });


    //From: http://stackoverflow.com/questions/3066586/get-string-in-yyyymmdd-format-from-js-date-object
    Date.prototype.toInputFormat = function() {
       var yyyy = this.getFullYear().toString();
       var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
       var dd  = this.getDate().toString();
       return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
    };
})(jQuery, this, document);

http://jsfiddle.net/MCzJ6/1

http://jsfiddle.net/MCzJ6/1

Hope this helps.

希望这可以帮助。

W