Skip to content

Instantly share code, notes, and snippets.

@bojidaryovchev
Last active November 13, 2021 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bojidaryovchev/cb7740e49f158a31039074f231a71750 to your computer and use it in GitHub Desktop.
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
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