Kartikey Vishwakarma Kartikey Vishwakarma - 22 days ago 6
Javascript Question

How to calculate difference of between two bootstrap datepicker?

Hi i have two bootstrap datepickers and i want to calculate the difference between the dates and show the number of days in a input box. Code:-

<input class="form-control datepicker" type="text" id="fdate" name="fdate">
<input class="form-control datepicker" type="text" id="tdate" name="tdate">
<input class="form-control" type="text" name="days" id="days">


JavaScript:-

<script>
$(function() {

$('#fdate').datepicker({
format: "dd-M-yy",
todayHighlight:'TRUE',
autoclose: true,
minDate: 0,
maxDate: '+1Y+6M',
onSelect: function (dateStr) {
var min = $(this).datepicker('getDate');
$("#tdate").datepicker('option', 'minDate', min || '0');
}
});

$('#tdate').datepicker({
format: "dd-M-yy",
todayHighlight:'TRUE',
autoclose: true,
minDate: '0',
maxDate: '+1Y+6M',
onSelect: function (dateStr) {
var max = $(this).datepicker('getDate');
$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M');
var start = $("#fdate").datepicker("getDate");
var end = $("#tdate").datepicker("getDate");
var days = (end - start) / (1000 * 60 * 60 * 24);
$("#days").val(days);
}
});
});
</script>


I have tried the above javascript to do it but it doesn't work. I am not sure whether it is the right way or not. Please help me in pointing out what is going wrong or if there is a better way of doing it. ANy help is highly appreciated.

Answer

You should use the onchange event of date picker. Chnage code according to the beloe]w code to get the date different like this

$(function() {

$('#fdate').datepicker({
    format: "dd-M-yy",
    todayHighlight:'TRUE',
    autoclose: true,
    minDate: 0,
    maxDate: '+1Y+6M',
    onSelect: function (dateStr) {
        var min = $(this).datepicker('getDate'); 
        $("#tdate").datepicker('option', 'minDate', min || '0');
    }
}); 

$('#tdate').datepicker({
    format: "dd-M-yy",
    todayHighlight:'TRUE',
    autoclose: true,
    minDate: '0',
    maxDate: '+1Y+6M',
    onSelect: function (dateStr) {

        var max = $(this).datepicker('getDate'); 
        $('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M');

    }
});

$("#tdate").datepicker().on('changeDate', function (ev) {
        var start = $("#fdate").val();
        var startD = new Date(start);
        var end = $("#tdate").val();
        var endD = new Date(end);
        var diff = parseInt((endD.getTime()-startD.getTime())/(24*3600*1000));
        $("#days").val(diff);
});

});

Working Example : https://plnkr.co/edit/D7gZnJBa3q6MiyCriT1U?p=preview