Skip to content

Instantly share code, notes, and snippets.

@snakeye
Created May 18, 2018 13:13
Show Gist options
  • Save snakeye/4c85bce7e6b2b7f9c745fe3cdab43bd2 to your computer and use it in GitHub Desktop.
Save snakeye/4c85bce7e6b2b7f9c745fe3cdab43bd2 to your computer and use it in GitHub Desktop.
Create month calendar grid in JavaScript
import moment from 'moment';
const getCalendarGrid = (year, month) => {
let ret = [];
const firstDayOfMonth = moment([year, month - 1, 1]);
const firstDayOfMonthIndex = firstDayOfMonth.day();
// grid row
let row = [];
// left padding of the first row with nulls
for (let i = 1; i < firstDayOfMonthIndex; i++) {
row.push(null);
}
let date = firstDayOfMonth;
// while we stay in the same month
while (date.month() === month - 1) {
// check if this row is already full
if (row.length === 7) {
ret.push(row);
// start new row
row = [];
}
// add current date to the row
row.push(date.date());
// next date
date = date.add(1, 'd')
}
// right padding of last row with nulls
for (let i = row.length; i < 7; i++) {
row.push(null)
}
ret.push(row);
//
return ret
};
export default getCalendarGrid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment