我正在使用 jqueryui 日期选择器 ( http://jqueryui.com/datepicker/#date-range ) 来选择安排活动的范围。我试图在更改开始日期时保持两个日期之间的偏移量。我能够在另一篇文章中找到合理的解决方案(使用 Jquery datepicker 添加选定日期的日期),但我发现当您选择一个早于当前选择的开始日期的日期时(例如:从 10/20 更改开始日期/2013 到 10/13/2013)它返回选择的最后日期而不是偏移日期。
<script>
$(document).ready(function() {
$( "#date_start" ).datepicker({
changeMonth: true,
numberOfMonths: 1,
dateFormat: "yy-mm-dd",
showOn: "both",
buttonImage: "images/smCal.gif",
buttonImageOnly: true,
constrainInput: true,
onSelect: function( selectedDate ) {
var stDate = $( "#curStartDate" ).val().split('-');
var enDate = $( "#date_end" ).val().split('-');
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(stDate[0],stDate[1],stDate[2]);
var secondDate = new Date(enDate[0],enDate[1],enDate[2]);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
if(!isNumber(diffDays)) {
diffDays = 0;
}
var date2 = $('#date_start').datepicker('getDate');
date2.setDate(date2.getDate()+diffDays);
$('#date_end').datepicker('setDate', date2);
$( "#curStartDate" ).val(selectedDate)
$( "#date_end" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#date_end" ).datepicker({
changeMonth: true,
numberOfMonths: 1,
dateFormat: "yy-mm-dd",
showOn: "both",
buttonImage: "images/smCal.gif",
buttonImageOnly: true,
constrainInput: true,
minDate:$( "#date_start" ).val()
});
$( "#curStartDate" ).val($( "#date_start" ).val());
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
</script>