使用jquery或Javascript向选定日期添加天数

Adding days to Selected Date with jquery or Javascript

本文关键字:日期 添加 jquery Javascript 使用      更新时间:2023-09-26

我有两个"文本框",我正在用jquery Datepicker在"文本框1"中选择日期。当我在Textbox1中选择日期时,我需要在Textbox2中自动显示一个日期,并将两天添加到Textbox1的选定日期。

例如:如果"文本框1"中选择的日期为"2015年12月31日"

在"文本框2"中显示日期为2016年2月2日…

我需要添加月份和年份也要添加并显示在Textbox2中。

有什么建议吗。。。。。。。。。。。?

$("#textbox1").datepicker({
    onSelect: function(dateText, inst) {
       var someDate=new Date(dateText);
       var duration =2; //day
       $("#textbox2").val(new Date(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000)));
    }
});​

我可能会使用momentjs来进行日期添加,这比尝试在纯JS中手动添加日期要干净得多。请参阅下面我的代码库,按照您在问题中描述的操作。

$(function() {
debugger;
  $('#textbox1').datepicker(
  {
    onSelect: function(dateText, inst) {
      var txtBox2 = $('#textbox2');
      var _sel = new moment(dateText);
      txtBox2.val(_sel.add('day',2));
    }
  });
});
<link href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<div>
  <input type="text" name="textbox1" id="textbox1">
  <input type="text" name="textbox2" id="textbox2" readonly="readonly">
</div>