我正在尝试使用jQuery datepicker仅在每年的7月和8月显示日期,除了8月31日之外它还有效。我也尝试过从7月中旬到9月中旬,它显示所有这些天除了无论如何,8月31日。
的jQuery
function generateDates(){
var availableDates = {};
var startYear = (new Date()).getUTCFullYear();
var endYear = 2050;
for(var currentYear = startYear; currentYear <= endYear; currentYear++){
//Loop over every year from current year to 2050
for (var d = new Date(currentYear, 7, 1); d <= new Date(currentYear, 8, 31); d.setDate(d.getDate() + 1)) {
availableDates[d.getUTCFullYear() + "-0" + d.getUTCMonth() + "-" + (d.getUTCDate() <= 9 ? "0" + d.getUTCDate() : d.getUTCDate())] = 1;
}
}
return availableDates;
}
$(function() {
var dates_allowed;
dates_allowed = generateDates();
$('#datepicker').datepicker({
// these aren't necessary, but if you happen to know them, why not
minDate: 0,
maxDate: new Date(2050, 8, 31),
// called for every date before it is displayed
beforeShowDay: function(date) {
// prepend values lower than 10 with 0
function addZero(no) {
if (no < 10){
return "0" + no;
} else {
return no;
}
}
var date_str = [
addZero(date.getFullYear()),
addZero(date.getMonth() + 1),
addZero(date.getDate())
].join('-');
if (dates_allowed[date_str]) {
return [true, 'good_date', 'This date is available'];
} else {
return [false, 'bad_date', 'We are sorry, this date is not available'];
}
}
});
});
HTML
<input id="datepicker" name="startdate" required>
非常感谢任何帮助。
此致
利
答案 0 :(得分:0)
JavaScript的月份基于0,所以8月你想要:
new Date(2050, 7, 31)
当你将月份设置为8,那是9月,所以你试图说9月31日,这是不存在的。同样,你想调整7月的指数。
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
答案 1 :(得分:0)
您可以使用getMonth
检查当前日期的月份是7月和8月,而不是检查每个日期,或者使用getYear
年份&lt; = 2050。
Js日期对象引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
代码:
$(function () {
$('#datepicker').datepicker({
// these aren't necessary, but if you happen to know them, why not
minDate: 0,
maxDate: new Date(2050, 7, 31),
// called for every date before it is displayed
beforeShowDay: function (date) {
if ((date.getMonth()==6 || date.getMonth()==7) && date.getYear()<=2050) {
return [true, 'good_date', 'This date is available'];
} else {
return [false, 'bad_date', 'We are sorry, this date is not available'];
}
}
});
});