Skip to content

Instantly share code, notes, and snippets.

@polRk
Created June 8, 2019 17:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polRk/45ff0cc02f433d081b1870ea82ee54d5 to your computer and use it in GitHub Desktop.
Save polRk/45ff0cc02f433d081b1870ea82ee54d5 to your computer and use it in GitHub Desktop.
Generate month days calendar on TypeScript and date-fns
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
}
@jordizle
Copy link

Legend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment