My jquery datepicker fields set a min and max date for the start and end fields, and that seems to throw off my attempts to write a script to calculate the number of days between the selected dates. I know others have asked this question, but every fix I've tried here on stackoverflow has failed to work, I suspect because of the customizations I have in my code. Can anyone please help me figure out how to take the code below and make it provide me a value in an input field called #totaldays? Thanks
// Calendar Dates
/* create an array of days which need to be disabled */
var disabledDays = ["11-13-2012","11-14-2012","11-15-2012","11-29-2012","11-30-2012"];
/* utility functions */
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1 || new Date() > date) {
return [false];
}
}
return [true];
}
//Block the Weekends
function noWeekendsOrHolidays(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays(date);
} else {
return noWeekend;
}
}
$(document).ready(function () {
$.datepicker.setDefaults({dateFormat: 'mm/dd/yy',minDate: +1,changeMonth: true,changeYear: true,numberOfMonths: 2,constrainInput:true,beforeShowDay:nationalDays,});
var selector = function (dateStr) {
var d1 = $('#datepicker_start').datepicker('getDate');
var d2 = $('#datepicker_end').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
$('#totaldays').val(diff);
}
$('#datepicker_start').datepicker({onSelect: function(selectedDate) {
var minDate = $(this).datepicker('getDate');
if (minDate) {minDate.setDate(minDate.getDate() + 3);}//min days requires
$('#datepicker_end').datepicker('option', 'minDate', minDate || 1); // Date + 1 or tomorrow by default
}});
$('#datepicker_end').datepicker({minDate: 1, onSelect: function(selectedDate) {
var maxDate = $(this).datepicker('getDate');
if (maxDate) {maxDate.setDate(maxDate.getDate() - 1);}
$('#datepicker_start').datepicker('option', 'maxDate', maxDate); // Date - 1
}});
$('#datepicker_start,#datepicker_end').change(selector)
});
Thanks!
I've created this function that I usually run in the onSelect
function of the datepickers to calculate the days between them :
function days() {
var a = $("#datepicker_start").datepicker('getDate').getTime(),
b = $("#datepicker_end").datepicker('getDate').getTime(),
c = 24*60*60*1000,
diffDays = Math.round(Math.abs((a - b)/(c)));
console.log(diffDays); //show difference
}
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With