我正在使用jqueryui datepicker(http://jqueryui.com/datepicker/#date-range)来选择用于安排事件的范围。我试图在开始日期改变时保持两个日期之间的偏移。我能够在另一篇文章(Add a day with selected date using Jquery datepicker)中找到合理的解决方案但我发现当你选择一个在当前所选开始日期之前的日期时(例如:将开始日期从2013年10月20日更改为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>
答案 0 :(得分:0)
我想出了这个问题。我将#date_end值的minDate设置为#date_start的当前值。因此,它会自动将日期选择更改为#date_start中最后选择日期的最新可用日期。因此,为了解决这个问题,我只需在尝试更改#date_end之前更改minDate。
新守则:
<script>
$(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 diffDays = daydiff(parseDate($('#curStartDate').val()), parseDate($('#date_end').val()));
if(!isNumber(diffDays)) diffDays = 0;
var date2 = $('#date_start').datepicker('getDate');
date2.setDate(date2.getDate()+diffDays);
$( "#date_end" ).datepicker( "option", "minDate", selectedDate );
$('#date_end').datepicker('setDate', date2);
$( "#curStartDate" ).val(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);
}
function parseDate(str) {
var mdy = str.split('-');
return new Date(mdy[0], mdy[1]-1, mdy[2]);
}
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);
}
</script>