Created
August 21, 2023 13:07
-
-
Save YonatanKra/c8ece3ff7bf7340d105e647044c77ba1 to your computer and use it in GitHub Desktop.
Implementation
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
export const buildCalendarGrid = ( | |
{ month, year }: Month, | |
locale: DatePickerLocale | |
): CalendarGrid => { | |
// Shift week days to start from firstDayOfWeek | |
const firstDayOfWeek = locale.firstDayOfWeek; | |
const getShiftedDay = (date: Date): number => | |
(date.getDay() - firstDayOfWeek + 7) % 7; | |
const grid: CalendarGridDate[][] = []; | |
const firstDay = new Date(year, month, 1); | |
const lastDay = new Date(year, month + 1, 0); | |
const daysInMonth = lastDay.getDate(); | |
const firstDayInWeek = getShiftedDay(firstDay); | |
let week: CalendarGridDate[] = []; | |
// Fill in the days before the first day of the month | |
for (let i = 0; i < firstDayInWeek; i++) { | |
const date = addDays(firstDay, i - firstDayInWeek); | |
week.push({ | |
date: formatDateStr(date), | |
label: `${date.getDate()}`, | |
isOutsideMonth: true, | |
}); | |
} | |
// Fill up days of the month | |
for (let i = 1; i <= daysInMonth; i++) { | |
week.push({ | |
date: formatDateStr(new Date(year, month, i)), | |
label: `${i}`, | |
isOutsideMonth: false, | |
}); | |
if (week.length === 7) { | |
grid.push(week); | |
week = []; | |
} | |
} | |
// Fill in the days after the last day of the month | |
const daysInLastWeek = week.length; | |
for (let i = daysInLastWeek; i < 7; i++) { | |
const date = addDays(lastDay, i - daysInLastWeek + 1); | |
week.push({ | |
date: formatDateStr(date), | |
label: `${date.getDate()}`, | |
isOutsideMonth: true, | |
}); | |
} | |
if (week.length > 0) { | |
grid.push(week); | |
} | |
return { | |
weekdays: getWeekdays(locale), | |
grid, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment