Last active
February 15, 2023 05:57
-
-
Save svapreddy/23e17073a90296aead22 to your computer and use it in GitHub Desktop.
A small util to generate Calendar Model for any given month and Year
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 */ | |
var days = new Array(42); | |
/* Here we calculate previous month dates for placeholders if starting day is not Sunday */ | |
var prevMonthDays = 0; | |
var prevMonth = new Date(year, month, 0); | |
prevMonth.setMonth(prevMonth.getMonth() - 1); | |
if(this.startDay !== 0) prevMonthDays = prevMonth.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 += 1) { | |
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; | |
} | |
days[i] = day.date; | |
} | |
this.days = days; | |
}; | |
/* Usage below */ | |
monthInformation.call(this/* Context */, 2015, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment