2

I am having fromdate and todate I want if user enters the from date and to date the gap between them should not be ore then 20 days. i.e if user enters from date='30/08/2018' to date='26/09/2018' here the gap is more then 20 days so i want to show a alert using jquery. Below is my code

 var today = new Date(new Date().getFullYear(), new Date().getMonth(),new Date().getDate());
 $('#startdate').datepicker({
    uiLibrary : 'bootstrap4',
    iconsLibrary : 'fontawesome',
    format : 'dd/mm/yyyy',
    maxDate : function() {
        return $('#enddate').val();
    }
 });
 $('#enddate').datepicker({
    uiLibrary : 'bootstrap4',
    iconsLibrary : 'fontawesome',
    format : 'dd/mm/yyyy',
    minDate : function() {
        return $('#startdate').val();
    }
 });
Amit chauhan
  • 540
  • 9
  • 22

2 Answers2

0

handle onchanged event in both the inputs and make a function 'checkDates()' which will compare the two dates and if the difference is more then 20 days make alert() .See the example code below

<input id="startdate" onchanged="checkDate()"/>
<input id="enddate" onchanged="checkDate()"/>
<script>
    function checkDate(){
        var start = $('#startdate').val();
        var end = $('#enddate').val();
        //convert strings to date for comparing
        var startDate = new Date(start);
        var endDate = new Date(end);
        // Calculate the day diffrence
        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
        var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));  
        if(diffDays > 20){
             alert("Days are more then twenty");
        }
    }
</script>

Please let me know if it worked.

Amit chauhan
  • 540
  • 9
  • 22
0

Try this.....

<input id="startDate" onchanged="myFunction()"/>
<input id="endDate" onchanged="myFunction()"/>
<script>
function myFunction(){
    var startDate = new Date($('#startDate').val());
    var endDate = new Date($('#endDate').val());
    var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));   
    if(diffDays > 20){
         alert("Days are more then twenty");
    }
}
</script>
Sooriya Dasanayake
  • 1,106
  • 1
  • 7
  • 14