I am a huge fan of JQuery’s datePicker. When I started using it there was no option of having it automatically set the year range based on the current year. This is what I did in order to achieve this:
//Add the date picker functionality. The selector is
// class based so it works for every form screen.
var now = new Date();
var thisYear = now.getYear();
var browser=navigator.appName;
if (browser==”Microsoft Internet Explorer”){
var startYear = thisYear – 70;
var endYear = thisYear + 20;
}
else {
var startYear = thisYear – 70 + 1900;
var endYear = thisYear + 20 + 1900;
}
$(“.datePickerControler”).datepicker({
changeFirstDay: false,
yearRange: + startYear +’:'+ endYear,
defaultDate: new Date(now)
});
The previous code snippet calculates, based on the current year, 20 years in the future and 70 years in the past. I then pass those values to the date picker to set a year range. You can also set this range by hard-coding it but, who wants to have to go back to their code every year and update the range?
For those unfamiliar with Javascript and/or JQuery I will break down that snippet.
//The Date object is used to work with dates and times. The following code creates a Date object and saves it in a variable called “now”:
var now = new Date();
//The getYear() method returns the year, as a two-digit OR a three/four-digit number. Set the “thisYear” variable to contain the value of the current year.
var thisYear = now.getYear();
//Retrieve the user’s browser info (I will explain why in a second). Save that to a variable called “browser”.
var browser=navigator.appName;
//Now we calculate, based on the current year, 20 years in the future and 70 in the past. Believe it or not, Internet Explorer actually does a spiffy job of interpreting the correct year. In any other browser we need to perform the calculation and then add 1900 in order to get the proper year value. This is why we need to know which browser the user is using. We do a basic if/else statement where we check for the value in the variable “browser”.
if (browser==”Microsoft Internet Explorer”){
var startYear = thisYear – 70;
var endYear = thisYear + 20;
}
else {
var startYear = thisYear – 70 + 1900;
var endYear = thisYear + 20 + 1900;
}
//Now we get into the plugin call itself. We used a class selector for our datePickers so we could reuse them throughout our site. We take the “startYear” and “endYear” variables and use them to set the “yearRange” property values. We also set the “defaultDate” property to default to the current date.
$(“.datePickerControler”).datepicker({
yearRange: + startYear +’:'+ endYear,
defaultDate: new Date(now)
});
That’s it! We have a datePicker that we set and forget. It will automatically update its date range.
Note: I used Jquery’s UI library version 1.5.3. The new version has more built in options which might render this method of calculation obsolete.



