我正试图使用javascript创建一个事件日历,但在将周一作为我的第一天时遇到了问题?
到目前为止,我得到的是:
const date = new Date();
const renderCalendar = () => {
date.setDate(1);
const monthDays = document.querySelector(".days");
const lastDay = new Date(
date.getFullYear(),
date.getMonth() + 1,
0
).getDate();
const prevLastDay = new Date(
date.getFullYear(),
date.getMonth(),
0
).getDate();
const firstDayIndex = date.getDay();
const lastDayIndex = new Date(
date.getFullYear(),
date.getMonth() + 1,
0
).getDay();
const nextDays = 7 - lastDayIndex - 1;
const months = [
"Januar",
"Februar",
"Marts",
"April",
"Maj",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"December",
];
document.querySelector(".date h1").innerHTML = months[date.getMonth()];
document.querySelector(".date p").innerHTML = new Date().toDateString();
let days = "";
for (let x = firstDayIndex; x > 0; x--) {
days += `<div class="prev-date">${prevLastDay - x + 1}</div>`;
}
for (let i = 1; i <= lastDay; i++) {
if (
i === new Date().getDate() &&
date.getMonth() === new Date().getMonth()
) {
days += `<div class="today">${i}</div>`;
} else {
days += `<div>${i}</div>`;
}
}
for (let j = 1; j <= nextDays; j++) {
days += `<div class="next-date">${j}</div>`;
monthDays.innerHTML = days;
}
};
document.querySelector(".prev").addEventListener("click", () => {
date.setMonth(date.getMonth() - 1);
renderCalendar();
});
document.querySelector(".next").addEventListener("click", () => {
date.setMonth(date.getMonth() + 1);
renderCalendar();
});
renderCalendar();
它把星期天定为一周的第一天?!?希望有人能帮忙并提前感谢:-(
默认情况下,getDay((方法返回sunday作为第一天或索引0。如果你想把周一作为第一天,你可以这样做:
const dayIndex=defaultDayIndex====0?6:defaultDayIndex-1;
const myDate = new Date('2021-12-07');
const defaultDayIndex = myDate.getDay();
// make monday first day of the week and sunday the last day
// monday will be index 0, and sunday will be index 6
const dayIndex = defaultDayIndex === 0 ? 6 : defaultDayIndex-1;