Created
July 17, 2019 22:19
-
-
Save faustienf/24ade33a938f05123f468567caef508d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
interface CalendarDay { | |
label: number; | |
timestamp: number; | |
isCurrentMonth: boolean; | |
} | |
type CalendarWeek = CalendarDay[]; | |
type Calendar = CalendarWeek[]; | |
/** | |
* @example | |
* getCalendar('2018-02-15') | |
* | |
* 29 30 31 01 02 03 04 | |
* 05 06 07 08 09 10 11 | |
* 12 13 14 15 16 17 18 | |
* 19 20 21 22 23 24 25 | |
* 26 27 28 01 02 03 04 | |
*/ | |
export function getCalendar(dateConstructValue: string | number | Date): Calendar { | |
const currentDate = new Date(dateConstructValue); | |
const currentMonth = currentDate.getMonth(); | |
const currentYear = currentDate.getFullYear(); | |
const calendarStartDate = new Date( | |
currentYear, | |
currentMonth, | |
); | |
const currentDay = calendarStartDate.getDay() | |
? calendarStartDate.getDay() | |
: 7; | |
calendarStartDate.setDate(calendarStartDate.getDate() - currentDay + 1); | |
let weekCounter = -1; | |
const calendar: Calendar = []; | |
while ( | |
currentMonth >= calendarStartDate.getMonth() | |
|| currentYear !== calendarStartDate.getFullYear() | |
) { | |
if (currentYear < calendarStartDate.getFullYear()) { | |
return calendar; | |
} | |
if (calendarStartDate.getDay() === 1) { | |
weekCounter += 1; | |
calendar[weekCounter] = Array.from( | |
{length: 7}, | |
(): CalendarDay => ({ | |
label: 0, | |
timestamp: 0, | |
isCurrentMonth: false, | |
}) | |
); | |
} | |
const currentWeek: CalendarDay[] = calendar[weekCounter]; | |
currentWeek.forEach((_, index): void => { | |
const calendarDay: CalendarDay = { | |
label: calendarStartDate.getDate(), | |
timestamp: calendarStartDate.getTime(), | |
isCurrentMonth: currentMonth === calendarStartDate.getMonth(), | |
}; | |
currentWeek[index] = calendarDay; | |
calendarStartDate.setDate(calendarStartDate.getDate() + 1); | |
}); | |
} | |
return calendar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment