使用日期选择器将日期添加到日期时出现问题。我知道这已被多次询问,但我们有不同的代码实现,这就是为什么我需要帮助谁知道这一点。添加天数时,必须排除星期六和星期日。我有这段代码:
<script type="text/javascript">
$(document).ready(function () {
$("#dt1").datepicker({
dateFormat: "dd-M-yy",
minDate: 0,
onSelect: function (date) {
var date2 = $('#dt1').datepicker('getDate');
date2.setDate(date2.getDate() + 2);
if (date2.getDay() != 0 && date2.getDay() != 6) // Skip weekends
{ $('#dt2').datepicker('setDate', date2);
//sets minDate to dt1 date + 1
$('#dt2').datepicker('option', 'minDate', date2);
}
}
});
$('#dt2').datepicker({
dateFormat: "dd-M-yy",
onClose: function () {
var dt1 = $('#dt1').datepicker('getDate');
console.log(dt1);
var dt2 = $('#dt2').datepicker('getDate');
if (dt2 <= dt1) {
var minDate = $('#dt2').datepicker('option', 'minDate');
$('#dt2').datepicker('setDate', minDate);
}
}
});
});
</script>
使用<script src="../js/jquery-1.9.1.js"></script>
这是我的输入字段:
<input type="text" id="dt1" name="date_borrow" pattern="alpha" required/>
<input type="text" id="dt2" name="date_will_return" pattern="alpha" required/>
我上面尝试添加的天数不起作用。我从那里错过了什么?
答案 0 :(得分:1)
$(document).ready(function () {
$("#dt1").datepicker({
dateFormat: 'dd-M-yy',
minDate: 0,
beforeShowDay: function (date) {
var day = date.getDay();
return [(day != 0 && day != 6), '']
},
onSelect: function (date) {
var date2 = $("#dt1").datepicker('getDate');
if (date2.getDay() == 5) {
date2.setDate(date2.getDate() + 3);
$("#dt2").datepicker('setDate', date2);
} else if (date2.getDay() == 3) {
date2.setDate(date2.getDate() + 2);
$("#dt2").datepicker('setDate', date2);
} else if (date2.getDay() == 4) {
date2.setDate(date2.getDate() + 4);
$("#dt2").datepicker('setDate', date2);
} else {
date2.setDate(date2.getDate() + 2);
$("#dt2").datepicker('setDate', date2);
}
}
})
$('#dt2').datepicker({
dateFormat: 'dd-M-yy',
minDate: 0,
beforeShowDay: function (date) {
var day = date.getDay();
return [(day != 0 && day != 6), '']
},
});
});
答案 1 :(得分:0)
如果有人想跳过某些工作日,我写了这段代码。可能这对任何人都有用。
function AddDays(date, offset, skipSunday, skipMonday, skipTueday, skipWednesday, skipThursday, skipFriday, skipSaturday) {
// If user wants to skip all days then return the same date because this is not possible
if (skipSunday && skipMonday && skipTueday && skipWednesday && skipThursday && skipFriday && skipSaturday) {
return date;
}
// Create array for all day numbers
var skipDays = [];
if (skipSunday) skipDays.push(0);
if (skipMonday) skipDays.push(1);
if (skipTueday) skipDays.push(2);
if (skipWednesday) skipDays.push(3);
if (skipThursday) skipDays.push(4);
if (skipFriday) skipDays.push(5);
if (skipSaturday) skipDays.push(6);
while (offset > 0) {
date.setDate(date.getDate() + 1);
if ($.inArray(date.getDay(), skipDays) <= -1) {
offset--
}
}
return date;
}