【问题标题】:Javscript setting first day as monday in calendarJavascript将日历中的第一天设置为星期一
【发布时间】:2021-09-04 23:04:07
【问题描述】:

我正在尝试使用 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();

它将星期天渲染为一周的第一天?!?希望有人可以帮助并提前感谢:-)

【问题讨论】:

    标签: javascript date calendar


    【解决方案1】:

    默认情况下,getDay() 方法返回星期日作为第一天或索引 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 2017-08-25
      相关资源
      最近更新 更多