Skip to content

Instantly share code, notes, and snippets.

@bsmirnov
Forked from svapreddy/CalendarMonth.js
Last active August 29, 2015 14:19
Show Gist options
  • Save bsmirnov/4feb29c818e6612c4991 to your computer and use it in GitHub Desktop.
Save bsmirnov/4feb29c818e6612c4991 to your computer and use it in GitHub Desktop.
/* 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(this/* Context */, 4, 2015);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment