Last active
February 6, 2020 10:42
-
-
Save jagomf/cd45b325c9cdc61301fe06a3febafa95 to your computer and use it in GitHub Desktop.
Generate a simple calendar which is an array of arrays
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
/** | |
* Generates a simple Calendar formatted as an array of arrays | |
* @param year Year for which calendar month is generated | |
* @param month Calendar month to be generated | |
* @param startWeekMonday Optional offset -- defaults to false (week starts on Sunday) | |
* @returns Main array (month) of arrays (weeks) of days | |
* @see Based on algorithm by github:lukeed/calendarize | |
*/ | |
private generateMonthCalendar(year: number, month: number, startWeekMonday = false) { | |
const res: number[][] = []; | |
const weekOffset = startWeekMonday ? 1 : 0; | |
let dayOfWeek = new Date(year, month, 1 - weekOffset).getDay(); | |
const daysInMonth = new Date(year, month + 1, 0).getDate(); | |
let day = 0; | |
while (day < daysInMonth) { | |
const week = Array(7); | |
for (let weekdayIterator = 0; weekdayIterator < 7;) { | |
while (weekdayIterator < dayOfWeek) { | |
week[weekdayIterator++] = 0; | |
} | |
week[weekdayIterator++] = ++day > daysInMonth ? 0 : day; | |
dayOfWeek = 0; | |
} | |
res.push(week); | |
} | |
return res; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment