Search code examples
jquerybootstrap-datepicker

Add 15 days to selected date in bootstrap datepicker


I am using bootstrap datepicker. I want to add 15 days to selected date.

$("#invoice_date").datepicker({
    format: 'yyyy-mm-dd',
}).on('changeDate', function(selected) {
    var minDate = new Date(selected.date.valueOf());
    var new_date = new Date(selected.date);
    new_date.setDate(new_date.getDate() + 15);
    $("#due_date").val(new_date);
    $('#due_date').datepicker('setStartDate', minDate);
});

<input type="text" name="invoice_date" id="invoice_date" value="2021-05-11" readonly>

<input type="text" name="due_date" id="due_date" value="2021-05-26" readonly>

When invoice date is selected, I want to add 15 days to the selected date in due date value


Solution

  • You can use .format() to get date in format of yyyy-mm-dd and then set this inside your input-box .

    Demo Code:

    $("#due_date").datepicker({
      format: 'yyyy-mm-dd'
    })
    $("#invoice_date").datepicker({
      format: 'yyyy-mm-dd',
    }).on('changeDate', function(selected) {
      var new_date = new Date(selected.format());
      new_date.setDate(new_date.getDate() + 15);
      $("#due_date").val(new_date.toISOString().slice(0, 10));
      $('#due_date').datepicker('setStartDate', selected.format());
    });
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
    
    <input type="text" name="invoice_date" id="invoice_date" value="2021-05-11" readonly>
    
    <input type="text" name="due_date" id="due_date" value="2021-05-26" readonly>