I am using the below function to set month information on context passed. It is working fine, but please review it and let me know if there are any potential flaws or any improvements in this code.
/* Expects month to be in 1-12 index based. */
var monthInformation = function (year, month) {
/* Create a date. Usually month in JS is 0-11 index based but here is a hack that can be used to calculate total days in a month */
var date = new Date(year, month, 0);
/* Get the total number of days in a month */
this.totalDays = date.getDate();
/* End day of month. Like Saturday is end of month etc. 0 means Sunday and 6 means Saturday */
this.endDay = date.getDay();
date.setDate(1);
/* Start day of month. Like Saturday is start of month etc. 0 means Sunday and 6 means Saturday */
this.startDay = date.getDay();
/* Here we generate days for 42 cells of a Month */
this.days = [];
/* Here we calculate previous month dates for placeholders if starting day is not Sunday */
var prevMonthDays = 0;
if (this.startDay !== 0) {
prevMonthDays = new Date(year, month - 1, 0).getDate() - this.startDay;
}
/* This is placeholder for next month. If month does not end on Saturday, placeholders for next days to fill other cells */
var count = 0;
// 42 = 7 columns * 6 rows. This is the standard number. Verify it with any standard Calendar
for (var i = 0; i < 42; i++) {
var day = {};
/* So start day is not Sunday, so we can display previous month dates. For that below we identify previous month dates */
if (i < this.startDay) {
day.date = (prevMonthDays = prevMonthDays + 1);
/* belong to next month dates. So, month does not end on Saturday. So here we get next month dates as placeholders */
} else if (i > this.totalDays + (this.startDay - 1)) {
day.date = (count = count + 1);
/* belong to current month dates. */
} else {
day.date = (i - this.startDay) + 1;
}
this.days[this.days.length] = day.date;
}
};
/* Usage below */
monthInformation.call(context, 4, 2015);
Date(year, month - 1, 0)
? \$\endgroup\$Date(year, month, 0);
is questionable. I think it is an undocumented feature and is implementation-specific \$\endgroup\$