Last active
July 6, 2023 21:13
-
-
Save bruceharrison1984/6176bad9054847a5d81a43f7503f6e9d to your computer and use it in GitHub Desktop.
Javascript - Get calendar view of month as an array of arrays representing a month, split into weeks 7 dates long.
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
/** | |
* This function will return an array of arrays representing a month as a 6*7 data table. This includes leading/trailing days. | |
* | |
* This only uses native JS objects, so no external libs are needed | |
* | |
* It only iterates a single time, so it is highly performant | |
* @param date The month/year of this Date object determines the calendar that will be generated. | |
* @returns Date[][] | |
*/ | |
const getCalendarView = (date: Date) => { | |
const startOfWeek = 0; // this can be adjusted to change the first day of the week. Sunday = 0, Monday = 1, etc | |
const startOfMonth = new Date(date.getFullYear(), date.getMonth(), 1); | |
let leadingDaysDifferential = startOfWeek - startOfMonth.getDay(); | |
if (leadingDaysDifferential > 0) { | |
//invert the leading days so slack is evenly divided between top/bottom | |
leadingDaysDifferential = -(7 - leadingDaysDifferential); | |
} | |
let dateIterator = new Date( | |
startOfMonth.getFullYear(), | |
startOfMonth.getMonth(), | |
startOfMonth.getDate() + leadingDaysDifferential | |
); | |
const dates: Date[] = [dateIterator]; | |
// fixed sized for 6x7 calendar body | |
for (let index = 0; index < 41; index++) { | |
dateIterator = new Date( | |
dateIterator.getFullYear(), | |
dateIterator.getMonth(), | |
dateIterator.getDate() + 1 | |
); | |
dates.push(dateIterator); | |
} | |
const monthView = [...Array(Math.ceil(dates.length / 7))].map(() => | |
dates.splice(0, 7) | |
); | |
return monthView; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment