I recently ran into a situation where I needed to know how many Monday’s were in a given month via javascript and figured I would make the function (which depends on Date extensions by ExtJS) for it available here in case anyone else runs into the same problem.
/*
* This function takes a date and determines how many of each day of the week
* are in the month.
*/
var getMonthlyDayOfWeekCount = function(sourceDate){
var iDate = Date.parseDate(sourceDate.format('m') + '/1/' + sourceDate.format('Y'), 'm/j/Y');
var days = [0, 0, 0, 0, 0, 0, 0];
while (iDate.format('m') == sourceDate.format('m')) {
days[iDate.format('w')]++;
iDate = iDate.add(Date.DAY, 1);
}
return days;
};
/*
* This function takes a date and returns an interger cotnaining the
* occurance of this day in the month.
*
* Useful for when you want to know if this is the 1st or 3rd Saturday in
* the month.
*/
var getDayInMonthCount = function(sourceDate){
var iDate = Date.parseDate(sourceDate.format('m') + '/1/' + sourceDate.format('Y'), 'm/j/Y');
count = 1;
while (iDate.format('m') == sourceDate.format('m')) {
if (iDate.format('z Y') == sourceDate.format('z Y')) {
return count;
}
if (iDate.format('w') == sourceDate.format('w')) {
count++;
}
iDate = iDate.add(Date.DAY, 1);
}
return count;
};