Skip to content

Instantly share code, notes, and snippets.

@sprobejames
Last active April 30, 2024 03:14
Show Gist options
  • Select an option

  • Save sprobejames/e26e18094ac1253c6a1c10395b911030 to your computer and use it in GitHub Desktop.

Select an option

Save sprobejames/e26e18094ac1253c6a1c10395b911030 to your computer and use it in GitHub Desktop.
const date = new Date(2024, 03, 25);
console.log(date.toLocaleString());
const range = 'month';
/** using native date **/
const generateDates = (date, range = 'month', splitIntoWeeks = true) => {
// the first day of the month
let startDate = new Date(
date.getFullYear(),
date.getMonth(),
range === 'month' ? 1 : date.getDate()
);
let limit = range === 'month' ? 42 : 7;
let calendarDays = [];
for (let day = 0; day < limit; day++) {
if (day === 0) {
const weekdayOfStartDate = startDate.getDay();
// if weekday of 1st day of the month is not sunday, change start date to the previous sunday before the start date
startDate.setDate(
startDate.getDate() - weekdayOfStartDate
)
} else {
startDate.setDate(startDate.getDate() + 1);
}
let calendarDay = {
currentMonth: startDate.getMonth() === date.getMonth(),
date: new Date(startDate).toLocaleString(),
}
// ignore last week if dates are not the same with the current date month
if (day === 35 && calendarDay.currentMonth == false) {
break;
}
calendarDays.push(calendarDay);
}
console.log(calendarDays);
return calendarDays;
};
/** using dayjs **/
dayjs.extend(dayjs_plugin_weekday);
const generateDates2 = (date, range = 'month') => {
let startDate = range === 'month' ? dayjs(date).startOf('month') : dayjs(date);
let limit = range === 'month' ? 42 : 7;
let calendarDays = [];
for (let day = 0; day < limit; day++) {
startDate = day === 0 ? startDate.weekday(0) : startDate.add(1, 'day');
let calendarDay = {
currentMonth: startDate.month() === dayjs(date).month(),
date: startDate.format(),
year: startDate.year(),
month: startDate.month(),
day: startDate.date(),
};
// ignore last week if dates are not the same with the current date month
if (day === 35 && calendarDay.currentMonth == false) {
break;
}
calendarDays.push(calendarDay);
}
/* const calendarDays = [...Array(limit)].map((_, day) => {
startDate = day === 0 ? startDate.weekday(0) : startDate.add(1, 'day');
let calendarDay = {
currentMonth: startDate.month() === dayjs(date).month(),
date: startDate.format(),
};
return calendarDay;
}) */
return calendarDays;
}
console.log(generateDates2(date, range));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment