twitter-bootstrap-3bootstrap-datetimepicker

Bootstrap DateTimePicker Set maxDate To The Second Field One Month After The First Field


I have 2 date fields. One "From" and one "To". I want when the user select from the first field the date ex "09/12/2015" the maxdate on the second field to be "09/01/2016". My code is:

<script type="text/javascript">
    $(function () {
        $('#from').datetimepicker({format: 'DD/MM/YYYY'});
        $('#to').datetimepicker({format: 'DD/MM/YYYY',useCurrent: false});

        $("#from").on("dp.change", function (e) {
            $('#to').data("DateTimePicker").minDate(e.date);
        });

        $("#to").on("dp.change", function (e) {
            $('#from').data("DateTimePicker").maxDate(e.date);
        });
    });
</script>

Can you help me? Thank You!


Solution

  • You can manipulate date using Moment, so you will have:

    $("#from").on("dp.change", function (e) {
      $('#to').data("DateTimePicker").minDate(e.date);
      var nextMonth = e.date.add(1, 'months');
      $('#to').data("DateTimePicker").maxDate(nextMonth);
    });
    

    Note that moment has a subtract method too, if you need to do the same operation in reverse.