Last active
November 13, 2021 21:10
-
-
Save bojidaryovchev/cb7740e49f158a31039074f231a71750 to your computer and use it in GitHub Desktop.
a function to get all dates surrounding a given date - it is intended to use when building calendars with 42 cells
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
getDates(date: Date): Date[] { | |
const dates: Date[] = []; | |
const firstDate: Date = new Date(new Date(date).setDate(1)); | |
const firstDateDay: number = firstDate.getDay(); | |
const daysBeforeFirst: number = firstDateDay - 1 === -1 ? 6 : firstDateDay - 1; | |
for (let i = daysBeforeFirst - 1; i >= 0; i--) { | |
dates.push(new Date(new Date(date).setDate(-i))); | |
} | |
const month: number = date.getMonth(); | |
const lastDate: number = new Date(new Date(new Date(date).setMonth(month + 1)).setDate(0)).getDate(); | |
for (let i = 1; i <= lastDate; i++) { | |
dates.push(new Date(new Date(date).setDate(i))); | |
} | |
const cellCount: number = 42; | |
for (let i = dates.length, j = 1; i < cellCount; i++, j++) { | |
dates.push(new Date(new Date(new Date(date).setMonth(month + 1)).setDate(j))); | |
} | |
return dates; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment