问题
I would like to disable different months in each of of datepicker years specifically the start year and the end year. I know I can use the beforeShowDay method to run some code that can return true and false to enable/disable dates. Right now I want to disable months Sept - Dec in 2005 and Nov + Dec in 2009 but I'm not completely sure how to do this.
When I log out date.getYear() I get numbers like 104 an 105 when I would expect to get 2014 and 2015 etc so I'm not sure how I can check the year to then go ahead and set the true/false values based on the min and max arrays I have created that will hold the months I want to exclude.
JS
var minYear = 2005,
maxYear = 2009,
excludeMinYearMonths = [8, 9, 10, 11],
excludeMaxYearMonths = [10, 11];
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange: minYear + ':' + maxYear,
beforeShowDay: function (date) {
console.log(date.getYear());
if (date.getYear() === minYear) {
if ($.inArray(date.getMonth(), excludeMinYearMonths) > -1) {
return [false, ''];
}
return [true, ''];
}
if (date.getYear() === maxYear) {
if ($.inArray(date.getMonth(), excludeMaxYearMonths) > -1) {
return [false, ''];
}
return [true, ''];
}
},
defaultDate: '01/01/05'
});
Jsfiddle: http://jsfiddle.net/qA9NT/18/
回答1:
You can start by reading a documentation of getYear(). There you will see why getFullYear() is used instead.
The
getYear()method returns the year minus 1900 in the specified date according to local time. BecausegetYear()does not return full years, it is no longer used and has been replaced by thegetFullYear()method.
Also, you forgot to define a default behavior for the non-excluded dates.
var minYear = 2005, maxYear = 2009, excludedMonths = {
2005: [8, 9, 10, 11],
2009: [10, 11]
};
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange: minYear + ':' + maxYear,
beforeShowDay: function (date) {
if (excludedMonths.hasOwnProperty(date.getFullYear())) {
if ($.inArray(date.getMonth(), excludedMonths[date.getFullYear()]) > -1) {
return [false, ''];
}
}
return [true, ''];
},
defaultDate: '01/01/05'
});
Check the updated live example.
来源:https://stackoverflow.com/questions/21031211/how-to-disable-different-months-in-each-of-the-datepicker-range-years-using-befo