Reputation: 131
I have this code, it counts days between two dates with jqueryUI datepicker.
How can I get rid of the first input entirely and just count days from today?
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
});
$("#dep_date").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: showDays
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" id="arr_date">
<input type="text" id="dep_date">
<input type="text" id="num_nights" disabled>
Upvotes: 1
Views: 431
Reputation: 14413
Use new Date()
and set its hours, minutes, seconds to 0
to match with the datepicker format. Also, use Math.round()
on the difference.
Then you can calculate as below:
function showDays() {
var start = new Date()
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
var end = $('#dep_date').datepicker('getDate');
if (!start || !end) return;
var days = Math.round((end - start) / 1000 / 60 / 60 / 24);
$('#num_nights').val(days);
}
$("#dep_date").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: showDays
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" id="dep_date">
<input type="text" id="num_nights" disabled>
Upvotes: 1