Week of Year in jQueryUI Datepicker

I needed to display week of year in a colum on the jqueryUI datepicker. Luckily it has the feature built in. Unluckily it has a quirk relative to the way we typically display calendars in the US with Sunday as the first day colum. At first I thought it was a bug, but technically it is not, so I guess it is better classified as a gotcha. Anyway, to get the week of year to display as we would expect in the US you need two pieces. First where you instantiate the datepicker:

1
2
3
4
5
6
7
8
$(".uiDatePicker").datepicker({
minDate: -1,
maxDate: '+10D',
defaultDate: +1,
hideIfNoPrevNext: true,
showWeek: true,
calculateWeek: myWeekCalc
});

The important argument there is the calculateWeek: myWeekCalc. Next you need to define the custom week of year calculator, in this case myWeekCalc:

1
2
3
4
5
6
7
8
9
function myWeekCalc(date) {
var checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Sunday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay()));
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}

I borrowed this from the jqueyUI source and tweaked it to calculate the week based on the Thursday in the row instead of the first day colum in the row. To me this makes sense given the way the ISO for week of year is determined. It seems to be working perfectly for me. Let me know if you use this and run into issues :)