如何使用bootstrap datetimepicker获取三个月后的日期?

时间:2018-12-06 11:00:14

标签: javascript jquery bootstrap-datetimepicker eonasdan-datetimepicker

我正在使用jquery datetimepicker&我有两个控件:

  1. 来自

我想在To控件中按照选定的日期在From控件中获得三个月的日期。

您尝试了什么:-

$(function () {
    $('.datePicker').datetimepicker({
    });


    $('body').on('blur', '.pcFrom', function () {
        var fromDate = $(this).val();
        $('.pcTo').val(fromDate);
    });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/eonasdan-bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" />


<script src="https://cdnjs.cloudflare.com/ajax/libs/eonasdan-bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group">
    <label>From</label>
    <input type="text" class="form-control datePicker pcFrom" data-date-format="MM-DD-YYYY">
</div>
  
<div class="form-group">
    <label>To</label>
    <input type="text" class="form-control pcTo">
</div>

1 个答案:

答案 0 :(得分:2)

您需要将值从日期选择器转换为Date(),然后通过添加所需的月份数来使用.setMonth()。然后,您需要在输出字段上再次重新设置其格式。

  $('.datePicker').datetimepicker();


  $(document).on('blur', '.pcFrom', function() {
    var fromDate = new Date($(this).val());
    var after3Months = fromDate.setMonth(fromDate.getMonth()+3);
    
    
    $('.pcTo').val("" + (fromDate.getMonth()+1) + "-" + fromDate.getDate() + "-" + fromDate.getFullYear());
  });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/eonasdan-bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" />


<script src="https://cdnjs.cloudflare.com/ajax/libs/eonasdan-bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group">
  <label>From</label>
  <input type="text" class="form-control datePicker pcFrom" data-date-format="MM-DD-YYYY">
</div>

<div class="form-group">
  <label>To</label>
  <input type="text" class="form-control pcTo">
</div>