Created
June 8, 2019 17:53
-
-
Save polRk/45ff0cc02f433d081b1870ea82ee54d5 to your computer and use it in GitHub Desktop.
Generate month days calendar on TypeScript and date-fns
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
import { isSameMonth, startOfMonth } from 'date-fns' | |
export const generateCalendar = ( | |
firstDateOfMonth: Date | |
): number[][] => { | |
const date = startOfMonth(firstDateOfMonth) | |
const getDay = (date: Date) => { | |
let day = date.getDay() | |
if (day === 0) day = 7 | |
return day - 1 | |
} | |
const calendar: number[][] = [[]] | |
for (let i = 0; i < getDay(date); i++) { | |
calendar[calendar.length - 1].push(0) | |
} | |
while (isSameMonth(date, firstDateOfMonth)) { | |
calendar[calendar.length - 1].push(date.getDate()) | |
if (getDay(date) % 7 == 6) { | |
calendar.push([]) | |
} | |
date.setDate(date.getDate() + 1) | |
} | |
if (getDay(date) != 0) { | |
for (let i = getDay(date); i < 7; i++) { | |
calendar[calendar.length - 1].push(0) | |
} | |
} | |
return calendar | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Legend