To select a date range, I use the Air Datepicker plugin.
To connect the plugin, I use CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"></script>
Plugin Initialization:
var maxdate = new Date();
maxdate.setDate(maxdate.getDate() + 14);
$('#datepicker').datepicker({
language: 'en',
autoClose: 'true',
clearButton: 'true',
minDate: new Date(),
maxDate: maxdate
})
HTML Code:
<input type='text' id='datepicker' data-range="true" data-multiple-dates-separator=" - " data-language="en" />
How to calculate the number of days in the range of selected dates?
For example:
You have chosen - 5 days
UPDATE: I found the appropriate code, but it is for the jQuery UI Datepicker:
function showDays() {
var start = $('#arr_date').datepicker('getDate');
var end = $('#dep_date').datepicker('getDate');
if (!start || !end) return;
var days = (end - start) / 1000 / 60 / 60 / 24;
$('#num_nights').val(days);
}
$("#arr_date").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: showDays,
onClose: function( selectedDate ) {
var dParts = selectedDate.split('-');
var in30Days = new Date(dParts[2] + '/' +
dParts[1] + '/' +
(+dParts[0] + 30)
);
$( "#dep_date" ).datepicker( "option", "minDate", in30Days );
}
});
$("#dep_date").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: showDays,
});
HTML Code:
<p>Choose your dates.</p><br/>
Start Date <input type="text" id="arr_date"><br/>
End Date <input type="text" id="dep_date"><br/>
No of Days <input type="text" id="num_nights" readonly>
How to make it work Air Datepicker?
Need your help! Thanks!
You can count no days by this way :
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
$(function() {
var myDatepicker = $('#count_days').datepicker({
language: 'en',
range:true,
multipleDatesSeparator : '-',
onSelect: function onSelect(selectedDates) {
console.log(selectedDates);
if(selectedDates !== undefined && selectedDates != '' && selectedDates.indexOf('-') > -1){
var mdy = selectedDates.split('-');
$("#arr_date").val(mdy[0]);
$("#dep_date").val(mdy[1]);
$("#num_nights").val(datediff(parseDate(mdy[0]), parseDate(mdy[1])));
}
}
})
});
<input type="text" name="count_days" id="count_days"class="datepicker-here"/>
<!--Date Format is like this : 03/01/2019 -->
<p>Choose your dates.</p><br/>
Start Date <input type="text" id="arr_date"><br/>
End Date <input type="text" id="dep_date"><br/>
No of Days <input type="text" id="num_nights" readonly>